I have been using some JavaScript techniques in the past to find the maximum and minimum number in an array. I recently stumbled upon a real fast and simple solution to find the max and min number in an array and thought of sharing it with all of you. Let me know what do you think of this method.

Add these two methods in your code:Array.prototype.max = function () { return Math.max.apply(Math, this); }; Array.prototype.min = function () { return Math.min.apply(Math, this); };

All you have to do now is call these methods on an array:

var max = [10, 12, 18, 24, 15].max(); var min = [10, 12, 18, 24, 15].min(); alert("Max Number: " + max + " Min Number: " + min);

The output is

The Math.max and Math.min can take unlimited arguments which is ideal when finding out the max and min in an array. The apply() function allows you to call a function with a this value and pass an array of any number of arguments. Starting with JavaScript 1.8.5, the arguments can be a generic array-like object instead of an array.

Tweet

## 2 comments:

Thanks for sharing such great tech info..!!

how would you use this method to find the min amounts of an array. ex

say i have two arrays:

[0233] and [1033]

I want to compare the two against each other and return the values that are in the array but are not in the same position.

So output would be 2 because 1 and 0 are in the array's but not in the same position.

Thanks

Post a Comment