Reputation: 20212
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.
Upvotes: 1
Views: 103
Reputation: 4184
You can "sort" the array by "nr" property in descending order and get first element "[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)
Upvotes: 3
Reputation: 1242
You can also use findIndex() method:
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]);
Upvotes: 1
Reputation: 386540
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);
Upvotes: 7