【问题标题】:Get element index of array of objects with the "highest" value for given key获取具有给定键的“最高”值的对象数组的元素索引
【发布时间】:2020-02-18 14:58:13
【问题描述】:

假设我有以下对象数组:

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

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

注意分数是动态的,“获胜”元素是最高值...

【问题讨论】:

标签: javascript


【解决方案1】:

您可以通过查看分数来获取键并减少索引。

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 index 是什么?
  • 我期待 3,因为它的最高分是 12。
  • 在我的真实示例中,我总是得到 11(这是列表中的最后一个元素)。也许是因为分数被记录为浮点数?
  • 不,抱歉,这行得通!愚蠢-我的关键是fuzzyRegexScore而不是score-快速编辑和繁荣!作品。谢谢。
【解决方案2】:

试试这个。使用 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)

【讨论】:

  • 这是分数的最大值,我想索引最高分数的对象。谢谢你的想法。
  • 我已从地图返回索引未得分尝试运行代码 sn-p
  • 嗯,可能是因为我有花车之类的......但使用你的例子总是返回 11。
【解决方案3】:

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

【讨论】:

  • 由于 OP 没有说明分数不能为负,我不会做出假设。这是有价值的。
  • 这不是价值:Number.NEGATIVE_INFINITY
  • 这很棒,而且很有效。我会让社区投票,看看随着时间的推移这是否应该是理想的赢家。谢谢@caramba
猜你喜欢
  • 1970-01-01
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
相关资源
最近更新 更多