Posted By

hellowouter on 03/30/12


math array max min maximum minimum apply

Versions (?)

Using Math.min and Math.max for an array

 / Published in: JavaScript


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.

  1. /* min/max number in an array */
  2. var numbers = [5, 6, 2, 3, 7];
  4. /* using Math.min/Math.max apply */
  5. var max = Math.max.apply(null, numbers); /* This about equal to Math.max(numbers[0], ...) or Math.max(5, 6, ..) */
  6. var min = Math.min.apply(null, numbers);

Report this snippet  

You need to login to post a comment.