Fast JavaScript Max/Min

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.

Posted: January 13th, 2007


Subscribe for email updates

8 Comments (Show Comments)



Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.


Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

John Resig Twitter Updates

@jeresig / Mastodon

Infrequent, short, updates and links.