I need a clean way of finding max for an array in JavaScript. Say it is arrayMax, then:
arrayMax([]) // => 0
arrayMax([1], [2]) // => 2
arrayMax([-1]) // => -1
What I've tried:
Math.max.apply(null, [1,2,3]) // => 3
But it doesn't work for:
Math.max.apply(null, []) // => -Infinity
Note that it's not an duplication with this question since I want the empty array to return 0, instead of -Infinity
You need a function that checks the length of the array:
function arrayMax(arr) {
    return arr.length ? Math.max.apply(null, arr) : 0;
};
Solutions that start with 0 will produce wrong results for arrays with only negative values.
With ES6 support, you can avoid the apply method and use the spread operator:
function arrayMax(arr) {
    return arr.length ? Math.max(...arr) : 0;
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With