Calculate min/max among set of numbers in JavaScript

I wanted to check the min/max among set of numbers in JavaScript but unfortunately there is no direct method available in JavaScript that can provide the min/max values among set of elements. But wait in JavaScript there is an method called ‘apply’, this is part of the parent Object which every thing is derived in JavaScript. In this article we would learn on how we can compute the min/max among set of elements using JavaScript without using any loops.

Function.prototype.apply allow use to call the function with the given this value and argument which takes an array of elements. This function is available with all the Objects used in JavaScript.

Function.apply(thisArg[, argsArray])

Now lets jump into the code required to compute min/max among set of numbers in JavaScript.
Assume we have set of number in an array

   var dataArray = [23,76,33,99,66,22,66,44];

Now i want to get the min among the above array, the traditional way is to loop through and get the minimum element but using apply function we have to write only one line of code.

  alert(Math.min.apply(null, dataArray));  //This would return 22
  alert(Math.max.apply(null, dataArray));  //This would return 99

Related Articles:

About Hitesh Agrawal

Wait... checking
Tagged . Bookmark the permalink.

One Response to Calculate min/max among set of numbers in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>