Micheal J. Roberts
Micheal J. Roberts

Reputation: 4180

Get element index of array of objects with the "highest" value for given key

Let's say I have the following array of objects:

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

What would be the quickest method for extract the position (index) of the element of the object with the highest score value...so, in the above case, the value would be index 3...

N.B. Scores are dynamic, and the "winning" element is the highest value...

Upvotes: 1

Views: 135

Answers (3)

caramba
caramba

Reputation: 22490

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

Upvotes: 1

Passionate Coder
Passionate Coder

Reputation: 7294

Try this. Use javascript max and map function to get value of index

 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) I think this will also give you correct result

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)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

You could get the keys and reduce the indices by checking the score.

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

Upvotes: 2

Related Questions