Get max and min value from array in JavaScript

前端 未结 7 1191
小鲜肉
小鲜肉 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:04

    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 });
    

提交回复
热议问题