I’ve been saving this technique for a while now – it’s simple, but it’s good. What’s the fastest way to find the largest, or smallest, number in an array?
There’s a bunch of implementations floating around – including some nicely object-oriented approaches in Prototype. However, none of them can compare to the raw simplicity of this:
Array.max = function( array ){ return Math.max.apply( Math, array ); }; Array.min = function( array ){ return Math.min.apply( Math, array ); };
The premise behind this technique is simple (and obvious once you see it): Just find any built-in JavaScript function that takes unlimited arguments – it’ll now be just as easy to adapt it for Array-wide use. By using JavaScript’s .apply() method on a built-in function you can pass in an array of unlimited arguments.
After “discovering” this for myself I found out that it’s mentioned in the “Rhino” book, which made me feel stupid. Oh well, it’s a great trick and its one that more people should know.
Jon B (January 13, 2007 at 5:24 am)
Why not write it as a prototype?
I thought extending Array wasn’t considered too harmful.
Jon B (January 13, 2007 at 5:36 am)
I thought Math.min/max only took two arguments? This is how most sites list it Math.min(x,y). It can handle more it seems, but are there limitations to this?
from devguru:
min Method
This method returns the lesser of the two numbers passed to it as arguments.
Martin (January 13, 2007 at 9:06 am)
This does not seem to work when the array is sparse.
[1, 4, undefined, 2, 3]
gives aNaN
John Resig (January 13, 2007 at 12:00 pm)
@JonB: It if you wish to extend the Prototype, you may do so. I don’t, as a matter of practice, participate in that.
Also, it does take an unlimited number of arguments – contrary to all of the documentation out there; which makes this all the more useful. Pop this into Firebug to see:
@Martin: That’s correct, so this would only work for a completely ‘dense’ array. If you’re working in situation with sparse arrays, then you could pre-process the arguments, like so:
Paul Spencer (January 15, 2007 at 1:33 pm)
My O’Reilly pocket reference says this:
Math.max(args…)
Returns the largest of the arguments. Returns -Infinity if there are no arguments. Returns NaN if any of the argumetns is Nan or is a non-numeric value that cannot be converted to a number. Prior to ECMA v3, this function requires exactly 2 arguments.
Although I doubt there are many browsers out there that don’t support this, you should likely make sure if you are writing code that could run in older browsers.
j.ales (March 2, 2007 at 4:33 am)
hello, the ‘Math’ arg in ‘apply’ is not requiered (any object will do)
try for instance:
var t = [1,2,3,5,4];
Math.max.apply(null, t);
gsdfgfd (April 12, 2007 at 5:23 am)
hgffgfggfhgfhg fg
Bogdan B (May 30, 2007 at 10:00 am)
Thanks people!