Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript max() for array column

Usually when I need to find the max value of an array I use this very simple code: var max = Math.max.apply(Math, array);

However, now I have a multidimensional array in which for each line I have an array with 5 columns. Is there a similar way to find the max value for a certain column? Right now I'm doing:

var maxFunc = function(data){
    var max = 0;
    data.forEach(function(value){
        max = Math.max(max, value[0]);
    });
    return max;
};

I was curious if there was a prettier/simpler way of doing this?

like image 647
ffleandro Avatar asked Jun 25 '12 13:06

ffleandro


1 Answers

I would write it as such:

Math.max.apply(Math, array.map(v => v[0]));

The array.map will transform the original array based on your picking logic, returning the first item in this case. The transformed array is then fed into Math.max()

To avoid creating a new array, you can also reduce the array to a single value:

array.reduce((max, current) => Math.max(max, current[0]), -Infinity)

As you can see, we need to add the initial value of -Infinity, which is returned if the array is empty.

like image 146
Ja͢ck Avatar answered Oct 15 '22 19:10

Ja͢ck