Get max and min value from array in JavaScript
Solution 1:
To get min/max value in array, you can use:
var _array = [1,3,2];
Math.max.apply(Math,_array); // 3
Math.min.apply(Math,_array); // 1
Solution 2:
Why not store it as an array of prices instead of object?
prices = []
$(allProducts).each(function () {
var price = parseFloat($(this).data('price'));
prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array
That way you can just
prices[0]; // cheapest
prices[prices.length - 1]; // most expensive
Note that you can do shift()
and pop()
to get min and max price respectively, but it will take off the price from the array.
Even better alternative is to use Sergei solution below, by using Math.max
and min
respectively.
EDIT:
I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7]
as 11.5
is treated as a string, and would come before the 3.x
in dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:
prices.sort(function(a, b) { return a - b });
Solution 3:
Instead of .each, another (perhaps more concise) approach to getting all those prices might be:
var prices = $(products).children("li").map(function() {
return $(this).prop("data-price");
}).get();
additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:
prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });
then use Sergey's solution above:
var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);
Solution 4:
if you have "scattered" (not inside an array) values you can use:
var max_value = Math.max(val1, val2, val3, val4, val5);
Solution 5:
arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);