Thread: Maximum value in an array View Single Post
 11-19-2012, 09:58 PM PM User | #1 felgall Master Coder     Join Date: Sep 2005 Location: Sydney, Australia Posts: 6,092 Thanks: 0 Thanked 579 Times in 569 Posts 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/ Beginners need to advise whether they want to learn "Latin" JavaScript for Netscape 3 or "Italian" JavaScript for modern browsers. Last edited by felgall; 11-19-2012 at 10:01 PM..