从 JavaScript 中的数组中获取最大值和最小值

Get max and min value from array in JavaScript

本文关键字:最大值 获取 最小值 数组 JavaScript      更新时间:2023-09-26

我正在从数据属性创建以下数组,我需要能够从中获取最高和最低值,以便以后可以将其传递给另一个函数。

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

我的列表项如下所示(为了可读性,我已削减):

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

价格上的快速控制台.log向我显示了我的数组,该数组似乎已排序,因此我可以获取我假设的第一个和最后一个元素,但目前数组中的名称和值是相同的,因此每当我尝试执行 price[0] 时,我都会未定义

[]
19.38   19.38
20.00   20.00
29.97   29.97
31.00   31.00

感觉这是一个非常简单的问题,所以请善待:)

要获取数组中的最小/最大值,可以使用:

var _array = [1,3,2];
Math.max.apply(Math,_array); // 3
Math.min.apply(Math,_array); // 1

为什么不将其存储为价格数组而不是对象?

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

这样你就可以

prices[0]; // cheapest
prices[prices.length - 1]; // most expensive

请注意,您可以执行shift()pop()分别获得最小和最高价格,但它会从数组中移除价格。

更好的选择是使用下面的谢尔盖解决方案,分别使用 Math.maxmin

编辑:

我意识到如果你有类似 [11.5, 3.1, 3.5, 3.7] 的东西,因为这11.5被视为字符串,并且会按字典顺序出现在3.x之前,这将是错误的,你需要传入自定义排序函数以确保它们确实被视为浮点数:

prices.sort(function(a, b) { return a - b });

而不是 .each,另一种(也许更简洁的)获取所有这些价格的方法可能是:

var prices = $(products).children("li").map(function() {
    return $(this).prop("data-price");
}).get();

此外,您可能需要考虑过滤数组以摆脱空数组或非数字数组值,以防它们存在:

prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });

然后使用上面的谢尔盖解决方案:

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

如果您有"分散"(不在数组内)的值,则可以使用:

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

使用它,它适用于静态数组和动态生成的数组。

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

当我使用尝试从下面的代码中找到最大值时,我遇到了问题

$('#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);

当我使用时,我变得'NAN'

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

用我的代码

使用 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>

如果需要在

不使用数学库或排序逻辑的情况下找到解决方案,以下解决方案可能会有所帮助。

要在 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; 

要查找最小值,

 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;

查找所有出现的最大值,(更改比较以获取所有最小值)

 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.