Get max and min value from array in JavaScript

Viewed 137525

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

8 Answers

Find largest and smallest number in an array with lodash.

var array = [1, 3, 2];
var func = _.over(Math.max, Math.min);
var [max, min] = func(...array);
// => [3, 1]
console.log(max);
console.log(min);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

If there exists requirement to find solution without using Math library, or Sorting logic, the below solutions might help.

To find the max value in javascript,

var max = -Infinity;
 for (var i = 0; i < arr.length; ++i) {
    if (arr[i] < max) continue;
    if (arr[i] > max) {
        max = arr[i];
 }
}
return max; 

To find the min value,

 var min = +Infinity;
 for (var i = 0; i < arr.length; ++i) {
    if (arr[i] > min) continue;
    if (arr[i] < min) {
        min = arr[i];
 }
}
return min;

To find all the occurrences of max values, (alter the comparisons to get all min values)

 var max = -Infinity, result = [];
  for (var i = 0; i < arr.length; ++i) {
   if (arr[i] < max) continue;
   if (arr[i] > max) {
      result = [];
      max = arr[i];
    }
   result.push(max);
  }
 return result; // return result.length to return the number of occurrences of max values.
Related