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?
I would write it as such:
Math.max.apply(Math, array.map(function(v) {
return 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()
This is a great application for Array.prototype.reduce
:
max = data.reduce(function(previousVal, currentItem, i, arr) {
return Math.max(previousVal, currentItem[0]);
}, Number.NEGATIVE_INFINITY);
This also avoids the bug in your code that would happen if all the values in data
are less than 0
. You should be comparing against Number.NEGATIVE_INFINITY
rather than 0
.
Alternatively, you could normalize the data before reducing to the max value:
max = data.map(function (d) {
return d[0];
}).reduce(function (p, c, i, arr) {
return Math.max(p, c);
});