JavaScript Quick Way to Find Max and Min Value in an Array

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

image

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.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Vinod said...

Thanks for sharing such great tech info..!!

Anonymous said...

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