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

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


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.


You can use the apply function, to call Math.max:

var array = [267, 306, 108];var largest = Math.max.apply(Math, array); // 306

How does it work?

The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)

So if we call:

Math.min.apply(Math, [1, 2, 3, 4]);

The apply function will execute:

Math.min(1, 2, 3, 4);

Note that the first parameter, the context, is not important for these functions since they are static. They will work regardless of what is passed as the context.


The easiest syntax, with the new spread operator:

var arr = [1, 2, 3];var max = Math.max(...arr);

Source : Mozilla MDN