views:

1233

answers:

3

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?

+14  A: 

Resig to the rescue:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Crescent Fresh
By the way, this is the second entry when you google for "javascript maximum array"...
schnaader
It's not de facto until Resig blogs it.
Crescent Fresh
It’s not a secret that 95% of the general population are too stupid to use Google.
Bombe
Christ. 90 rep in 3 minutes for an answer that would have been faster to google.
Crescent Fresh
Ah, but now it has the **SO Sticker of Quality** affixed to it in an only slightly-crooked fashion!
Shog9
FWIW, if performance is a factor in your solution, I would **test that** compared to your own easily-coded function to make sure it performs well. We tend to assume that the native implementation will be faster; in fact, the cost of the `apply` call can wash that out very easily.
T.J. Crowder
By the way, this only works reliably with number values (not, say, string ones), whereas `sort` -based solution works with strings and objects.
kangax
@kangax: on the other hand, if you have a mix of numbers and string representations of numbers, the `sort()` -based method *may* not do what you expect. Try: `["7", "50", 300]`...
Shog9
+5  A: 

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

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

How it works?

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.

CMS
+4  A: 

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

[267, 306, 108].sort(function(a,b){return b-a;})[0]
Gumbo
I would assume you could also just sort and get the last item...?
Shog9
@Shog9: Yes, but you would need to specify the comparison function on your own: `sort(function(a,b){return b-a;})`
Gumbo
Ah. I was thinking more like: `[...].sort().pop()`
Shog9
@Shog9: Nice, didn’t think of that.
Gumbo
Ant. Howitzer.
Robert L
aSeptik