In short, this works:
[1, 2, 3].reduce(function (a, b) { return Math.max(a, b); });
=> 3
But this doesn't:
[1, 2, 3].reduce(Math.max);
=> NaN
Pure puzzlement.
This is in Firefox 3.5.9, which I presume is using the mozilla standard implementation of reduce, FWIW.
In short, this works:
[1, 2, 3].reduce(function (a, b) { return Math.max(a, b); });
=> 3
But this doesn't:
[1, 2, 3].reduce(Math.max);
=> NaN
Pure puzzlement.
This is in Firefox 3.5.9, which I presume is using the mozilla standard implementation of reduce, FWIW.
Share Improve this question asked May 18, 2010 at 11:21 cemerickcemerick 5,9165 gold badges32 silver badges52 bronze badges 4 |3 Answers
Reset to default 22Math.max
can be used as a higher-order function. The problem is .reduce
will call the function with 4 arguments:
Math.max(accumulator, value, index, the_array)
here is the_array
is an array, so Math.max
returns NaN. I don't think there's simpler way to discard the last 2 arguments.
Math.max.apply(Math, [1, 2, 3]);
//3
Not exactly a higher order use, but this also works:
Math.max(...myArray);
(reduce + '(1 2 3 4 5))
– Ron Inbar Commented Oct 20, 2017 at 16:36