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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11985341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:56:01  来源:igfitidea点击:

Get max and min value from array in JavaScript

javascriptjqueryarraysposition

提问by RJB

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

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

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

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

回答by Serg Hospodarets

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

回答by Andreas Wong

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.

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

Even better alternative is to use Sergei solution below, by using Math.maxand minrespectively.

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

EDIT:

编辑:

I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7]as 11.5is treated as a string, and would come beforethe 3.xin dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:

我意识到,这将是错误的,如果你有类似[11.5, 3.1, 3.5, 3.7]11.5被视为一个字符串,并且会来之前3.x在字典顺序,你需要自定义排序函数来传递,以确保他们确实视为浮动:

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

回答by billynoah

Instead of .each, another (perhaps more concise) approach to getting all those prices might be:

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

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

回答by rvandoni

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

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

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

回答by MIqayel Ishkhanyan

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

回答by Penny Liu

Find largest and smallest number in an array with lodash.

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

回答by Sodhi saab

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

'NAN'在使用时得到

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

with my code

用我的代码