简体   繁体   English

返回数组索引,其中subscore.js的子值最大

[英]Return array index where sub value is max with underscore.js

I have a setup like this: 我有这样的设置:

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

I want to get the docs[index] of the one with the most edits. 我想获得编辑次数最多的docs[index]

Using Underscore I can get the appropriate array (ie the value docs[1] ), but I still don't know the actual index in relation to docs . 使用Underscore,我可以获得适当的数组(即值docs[1] ),但是我仍然不知道与docs相关的实际索引。

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

Any help would be greatly appreciated. 任何帮助将不胜感激。

To do it without a library, iterate over the array (possibly with reduce ), storing the highest number so far and the highest index so far in a variable, reassigning both when the item being iterated over is higher: 要在没有库的情况下执行此操作,请遍历数组(可能使用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); 

Another way, with findIndex , and spreading the edits into Math.max (less code, but requires iterating twice): 另一种方法是,使用findIndex ,并将edits传播到Math.max (更少的代码,但是需要迭代两次):

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

Just use maxBy 只需使用maxBy

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)

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

Pure JS way 纯JS方式

const result2 = docs.reduce((result, { edits }) => edits > result ? edits : result, Number.MIN_SAFE_INTEGER)

console.log(result2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM