Bohdan Bohdan - 4 months ago 32
Javascript Question

How to get index of the max value in array of objects?

I've got an array with following format:

var dataset = [{
date: '1',
value: '55'
}, {
date: '2',
value: '52'
}, {
date: '3',
value: '47'
}];


And I'm getting the maximum value in it by:

var maxValue = Math.max.apply(Math, dataset.map(function(o) {
return o.value;
}));


It works very well, there's nothing to worry about. But how I can obtain an index of the maxValue?

I've tried indexOf() (which returns me -1 all the time), jQuery inArray() as well as reduce() but none of them work properly.

I guess there's a more cleaner way by iterating all elements to get the index.

Thanks in advance.

Answer

As an alternative with Array.forEach

var dataset = [{date:'1',value:'55'},{date:'2',value:'56'},{date:'3',value:'47'}],
    max = -Infinity,
    key;  

dataset.forEach(function (v, k) { 
    if (max < +v.value) { 
        max = +v.value; 
        key = k; 
    }
});

console.log(key);

Comments