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:

  1. Array.max = function( array ){
  2.     return Math.max.apply( Math, array );
  3. };
  4.  
  5. Array.min = function( array ){
  6.     return Math.min.apply( Math, array );
  7. };

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


If you particularly enjoy my work, I appreciate donations given with Gittip.

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.

Ukiyo-e Database and Search

Ukiyo-e.org

Japanese woodblock print database and search engine.


John Resig Twitter Updates

@jeresig

Infrequent, short, updates and links.


via Ad Packs