Alex Rivera | Logout

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

Asked 2009-09-04T14:17:51.780
222

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?

Edit
Report

2 Answers

208

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.

answered 2009-09-04T14:19:43.773
33

You could sort the array in descending order and get the first item:

[267, 306, 108].sort(function(a,b){return b-a;})[0]
answered 2009-09-04T14:20:28.673

Your Answer