Return to Snippet

Revision: 56483
at March 30, 2012 18:36 by hellowouter


Initial Code
/* min/max number in an array */
var numbers = [5, 6, 2, 3, 7];

/* using Math.min/Math.max apply */
var max = Math.max.apply(null, numbers); /* This about equal to Math.max(numbers[0], ...) or Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);

Initial URL
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply

Initial Description
Clever usage of apply allows you to use built-ins functions for some tasks that otherwise probably would have been written by looping over the array values. As an example here we are going to use Math.max/Math.min to find out the maximum/minimum value in an array.

Initial Title
Using Math.min and Math.max for an array

Initial Tags
math, array

Initial Language
JavaScript