Monday, 22 October 2012

Find the min and max value of a javascript array


I'd like to quickly find the minimum and maximum values stored in a javascript array without having kept track of them in advance, and without using a loop.


One of the easiest ways to do this is to use Function.prototype.apply with Math.min and Math.max, e.g.

var min = Math.min.apply(null, myArrOfNumbers);
var max = Math.max.apply(null, myArrOfNumbers);


When expanded, note that the first of the above examples is roughly equivalent to Math.min(myArrOfNumbers[0], myArrOfNumbers[1], ...). With that in mind, it should be cautioned that the solution in this post should only be used with small arrays, as many javascript engines have a limit as to how many arguments a function can accept, leading to unpredictable behaviour when this limit is exceeded.

For those interested, see more details in the following linked reference for javascript's Function.prototype.apply.


No comments:

Post a Comment