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 · Tags: tips, javascript, programming

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.


Current Projects

jQuery JavaScript Library

jQuery

Comprehensive DOM, Event, Animation, and Ajax JavaScript Library.

Recent Projects

Pro JavaScript Techniques

JavaScript Book

The best techniques for professional JavaScript. Published by Apress.


Hosting provided by the cool dudes at Engine Yard.