felgall

11-19-2012, 09:58 PM

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.

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:

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.

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

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:

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.