Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max and min value from array in JavaScript

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 :)

like image 545
RJB Avatar asked Aug 16 '12 10:08

RJB


People also ask

What is min and max JavaScript?

max() function returns the largest of zero or more numbers. and min function of Math object. The Math. min() function returns the smallest of zero or more numbers.


1 Answers

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 
like image 132
Serg Hospodarets Avatar answered Sep 23 '22 12:09

Serg Hospodarets