How might I find the largest number contained in a JavaScript array?

dotty picture dotty · Sep 4, 2009 · Viewed 249.3k times · Source

I have a simple JavaScript Array object containing a few numbers.

[267, 306, 108]

Is there a function that would find the largest number in this array?

Answer

Crescent Fresh picture Crescent Fresh · Sep 4, 2009

Resig to the rescue:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Warning: since the maximum number of arguments is as low as 65535 on some VMs, use a for loop if you're not certain the array is that small.