Get max and min value from array in JavaScript

JavascriptJqueryArraysPosition

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

if you have "scattered" (not inside an array) values you can use:

var max_value = Math.max(val1, val2, val3, val4, val5);

Solution 5 - Javascript

arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);

Solution 6 - Javascript

use this and it works on both the static arrays and dynamically generated arrays.

var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );

I had the issue when I use trying to find max value from code below

$('#myTabs').find('li.active').prevAll().andSelf().each(function () {
            newGetWidthOfEachTab.push(parseInt($(this).outerWidth()));
        });

        for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
            newWidthOfEachTabTotal += newGetWidthOfEachTab[i];
            newGetWidthOfEachTabArr.push(parseInt(newWidthOfEachTabTotal));
        }

        getMaxValue = Math.max.apply(Math, array);

I was getting 'NAN' when I use

    var max_value = Math.max(12, 21, 23, 2323, 23);

with my code

Solution 7 - Javascript

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>

Solution 8 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRJBView Question on Stackoverflow
Solution 1 - JavascriptSerg HospodaretsView Answer on Stackoverflow
Solution 2 - JavascriptAndreas WongView Answer on Stackoverflow
Solution 3 - JavascriptEaten by a GrueView Answer on Stackoverflow
Solution 4 - JavascriptrvandoniView Answer on Stackoverflow
Solution 5 - JavascriptMIqayel IshkhanyanView Answer on Stackoverflow
Solution 6 - JavascriptSodhi saabView Answer on Stackoverflow
Solution 7 - JavascriptPenny LiuView Answer on Stackoverflow
Solution 8 - JavascriptSasi Kumar MView Answer on Stackoverflow