Get max and min value from array in JavaScript

RJB picture RJB · Aug 16, 2012 · Viewed 125.8k times · Source

I am creating the following array from data attributes and I need to be able to grab the highest and lowest value from it so I can pass it to another function later on.

var allProducts = $(products).children("li");
prices = []
$(allProducts).each(function () {
    var price = parseFloat($(this).data('price'));
    prices[price] = price;
});
console.log(prices[0]) <!-- this returns undefined

My list items look like this (I have cut down for readability):

<li data-price="29.97"><a href="#">Product</a></li>
<li data-price="31.00"><a href="#">Product</a></li>
<li data-price="19.38"><a href="#">Product</a></li>
<li data-price="20.00"><a href="#">Product</a></li>

A quick console.log on prices shows me my array which appears to be sorted so I could grab the first and last element I assume, but presently the names and values in the array are the same so whenever I try and do a prices[0], I get undefined

[]
19.38   19.38
20.00   20.00
29.97   29.97
31.00   31.00

Got a feeling this is a stupidly easy question, so please be kind :)

Answer

Serg Hospodarets picture Serg Hospodarets · Aug 16, 2012

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