views:

48

answers:

1

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.

+5  A: 

Math.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.

KennyTM
That's what I get for not reading the MDC docs closely enough. Crazy idea of a reduce fn, IMO, but hey, it's javascript! ;-) Thanks.
Chas Emerick