[英]Get element index of array of objects with the "highest" value for given key
Let's say I have the following array of objects:假设我有以下对象数组:
[
{ name: 'january', score: 3.02 },
{ name: 'february', score: 1.02 },
{ name: 'march', score: 0 },
{ name: 'april', score: 12 },
]
What would be the quickest method for extract the position ( index
) of the element of the object with the highest score value...so, in the above case, the value would be index 3
...提取具有最高分值的对象元素的位置( index
)的最快方法是什么...因此,在上述情况下,该值将是 index 3
...
NB Scores are dynamic, and the "winning" element is the highest value... NB分数是动态的,“获胜”元素是最高值……
You could get the keys and reduce the indices by checking the score.您可以通过检查分数来获取密钥并减少索引。
var data = [{ name: 'january', score: 3.02 }, { name: 'february', score: 1.02 }, { name: 'march', score: 0 }, { name: 'april', score: 12 }], index = [...data.keys()].reduce((a, b) => data[a].score > data[b].score ? a : b); console.log(index);
var data = [ { name: 'january', score: 3.02 }, { name: 'february', score: 1.02 }, { name: 'march', score: 0 }, { name: 'april', score: 12 }, ]; var resultValue = null; var tempValue = Number.NEGATIVE_INFINITY; data.forEach(function(element, index) { if(element.score > tempValue) { tempValue = element.score; resultValue = index; } }); console.log(resultValue);
Try this.尝试这个。 Use javascript max and map function to get value of index使用 javascript max 和 map 函数获取索引值
var data = [ { name: 'january', score: 3.02 }, { name: 'february', score: 1.02 }, { name: 'march', score: 0 }, { name: 'april', score: 12 } ]; var maxValue = Math.max.apply(Math, data.map(function(row,index) { return index; })) console.log(maxValue)
2) I think this will also give you correct result 2)我认为这也会给你正确的结果
var data = [ { name: 'april', score: 1 }, { name: 'january', score: 3.02 }, { name: 'february', score: 11.02 }, { name: 'march', score: 2 } ]; var maxValue = Math.max.apply(Math, data.map(function(row) { return row.score; })) var key = data.findIndex((row,index)=>{ if(row.score ===maxValue){return true}}) console.log(key)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.