How to use Math.max, etc. as higher-order functions

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.

Answers


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.


Math.max.apply(Math, [1, 2, 3]);
//3

Need Your Help

How can I save information locally in my chrome extension?

javascript google-chrome google-chrome-extension

I want my chrome extension to save some information, and I'm not sure how to start the code...

How to add MVC 5 authentication to Unity IoC?

c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

I'm currently working on implementing the new ASP.NET MVC 5 out-of-the box authentication into my application. However when using Unity as my IoC, I cannot use any portion of the AccountController