View Single Post
Old 11-19-2012, 08:58 PM   PM User | #1
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,462
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Maximum value in an array

I have noticed a number of queries where someone needs to get the maximum (or sometimes the minimum) value that is contained in an array. Just about every solution offered involves multiple lines of code and a loop but there is actually a single JavaScript command that will retrieve the maximum value from an array directly with only the one statement and no loop being required.

Let's start with an array of numbers where we need to get the maximum value.

Code:
ary = [4,7,-2,55,2,12];
It doesn't really matter how we get those numbers into the array, all that matters is that we have an array and want to get the maximum value. To get the maximum value from the array we run the following code:

Code:
max = Math.max.apply(Math,ary);
The variable max now contains the maximum value from the array called ary (if you run both these statements then max contains 55).

To get the minimum value just substitute Math.min instead of Math.max

No loops and just a single call and we have the answer.

Where JavaScript provides a single call that gives the answer you should not try to reinvent the wheel by writing your own less efficient code to do the same thing. There are enough things that JavaScript doesn't provide single commands for that can be used instead in homework questions where a loop would be required (or whatever the question is intended to test) without asking questions that are better solved wothout using the construct that the question is supposed to be testing.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 11-19-2012 at 09:01 PM..
felgall is offline   Reply With Quote