How to find min/max value from an array using JavaScript

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 really 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.

var array =  [ "18", "16", "21", "5", "25", "10", "20" ];
var minvalue  = Math.min.apply(null, array);
var maxvalue  = Math.max.apply(null, array);
console.log("minvalue= "+minvalue);			
console.log("maxvalue= "+maxvalue);	

Output

minvalue= 5
maxvalue= 25

Another Example

var array =  [11,4,2,5,9,20];
var minvalue  = Math.min.apply(null, array);
var maxvalue  = Math.max.apply(null, array);
console.log("minvalue= "+minvalue);			
console.log("maxvalue= "+maxvalue);

Output

minvalue= 2  
maxvalue= 20

Leave a Reply

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