简体   繁体   English

从包含多个对象的数组中返回编号最高的对象

[英]Return object with highest number from array containing multiple objects

I was able to figure out how to return the highest number from a associative array with multiple objects. 我能够弄清楚如何从具有多个对象的关联数组中返回最大的数字。 But I need the whole object. 但是我需要整个对象。

I prepared this example: 我准备了这个例子:

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

I need the index or the whole object. 我需要索引或整个对象。 I need to show the text from the object with the highest number. 我需要显示对象编号最高的文本。

You could reduce the array by selecting the one with a greater value. 您可以通过选择一个更大的值来减少数组。

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

You can "sort" the array by "nr" property in descending order and get first element "[0]" 您可以按降序按“ nr”属性对数组进行“排序”,并获得第一个元素“ [0]”

 var data = [ { nr: 235, text: "foo" } ,{ nr: 351, text: "bar" } ]; // slice added so that original data is not mutated var result = data.slice(0).sort((a,b) => b.nr - a.nr)[0] console.log(result) 

You can also use findIndex() method: 您也可以使用findIndex()方法:

 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 = data.findIndex(function(ln) { return ln.nr === highestNr; }); console.log("Highest 'nr': " + highestNr); console.log("Index at nr "+ highestNr + ": " + index); //console.log(data[index]); 

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

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