首页 > 解决方案 > 从包含多个对象的数组中返回编号最大的对象

问题描述

我能够弄清楚如何从具有多个对象的关联数组中返回最高数字。但我需要整个对象。

我准备了这个例子:

var data = [
     { nr: 235, text: "foo" }
    ,{ nr: 351, text: "bar" }
];

var highestNr = Math.max.apply(null, Object.keys(data).map(function(e) {
             return data[e]['nr'];
         }));
                
var index = "???";

console.log("Highest 'nr': " + highestNr);
console.log("Index at nr "+ highestNr + ": " + index);

//console.log(data[index]);

我需要索引或整个对象。我需要显示来自具有最高数字的对象的文本。

标签: javascript

解决方案


您可以通过选择具有更大值的数组来减少数组。

var data = [{ nr: 235, text: "foo" }, { nr: 351, text: "bar" }], 
    topNr = data.reduce((a, b) => a.nr > b.nr ? a : b);

console.log(topNr);


推荐阅读