Bohdan Bohdan - 9 months ago 63
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, {
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.


As an alternative with Array.forEach

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

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