Black
Black

Reputation: 20212

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.

Upvotes: 1

Views: 103

Answers (3)

Nitish Narang
Nitish Narang

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

Roland Ruul
Roland Ruul

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

Nina Scholz
Nina Scholz

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

Related Questions