返回数组索引,其中subscore.js

时间:2019-01-04 07:28:50

标签: javascript arrays underscore.js

我有这样的设置:

docs[0]['edits'] = 1;
docs[1]['edits'] = 2;

我想获得编辑次数最多的docs[index]

使用下划线,我可以获得适当的数组(即值docs[1]),但是我仍然不知道与docs相关的实际索引。

_.max(docs, function(doc) { return doc['edits']; });

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

要在没有库的情况下执行此操作,请遍历数组(可能使用reduce),将迄今为止的最高编号和迄今为止的最高索引存储在变量中,并在要遍历的项目较高时重新分配:

const edits = [
  3,
  4,
  5,
  0,
  0
];

let highestNum = edits[0];
const highestIndex = edits.reduce((highestIndexSoFar, num, i) => {
  if (num > highestNum) {
    highestNum = num;
    return i;
  }
  return highestIndexSoFar;
}, 0);

console.log(highestIndex);

另一种方法,使用findIndex,然后将edits扩展到Math.max中(更少的代码,但是需要迭代两次):

const edits = [
  3,
  4,
  5,
  0,
  0
];
const highest = Math.max(...edits);
const highestIndex = edits.indexOf(highest);

console.log(highestIndex);

答案 1 :(得分:1)

只需使用subject1:111 Ref[1442.1] 1.19e-10 [line-break] subject1:123 Ref[1421.1] 5.17e-10 [line-break] subject1:134 Ref[4215.1] 2.12e-10 [line-break] subject1:151 Ref[6531.1] 6.17e-10 [line-break]

maxBy

https://repl.it/@NickMasters/DigitalUtterTechnologies

纯JS方式

const _ = require('lodash');

const docs = [{'edits': 1}, {'edits': 2}, {'edits': 0}, {'edits': 4}, {'edits': 3}]

const result = _.maxBy(docs, a => a.edits)

console.log(result)