繁体   English   中英

获取具有给定键的“最高”值的对象数组的元素索引

[英]Get element index of array of objects with the "highest" value for given key

假设我有以下对象数组:

[
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 },
]

提取具有最高分值的对象元素的位置( index )的最快方法是什么...因此,在上述情况下,该值将是 index 3 ...

NB分数是动态的,“获胜”元素是最高值……

您可以通过检查分数来获取密钥并减少索引。

 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);

尝试这个。 使用 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)我认为这也会给你正确的结果

 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.

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