Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max for an array, 0 if array is empty

Tags:

javascript

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

like image 405
songyy Avatar asked Oct 31 '25 02:10

songyy


1 Answers

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;
};
like image 59
trincot Avatar answered Nov 02 '25 17:11

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!