Get max and min value from array in JavaScript

前端 未结 7 1176
小鲜肉
小鲜肉 2020-12-07 22:26

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.

相关标签:
7条回答
  • 2020-12-07 23:09

    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);
    
    0 讨论(0)
提交回复
热议问题