简体   繁体   English

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

[英]Get max and min value from array in JavaScript

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 :) 有一种感觉这是一个非常简单的问题,所以请善待:)

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

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.max and min respectively. 更好的选择是使用下面的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.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: 我意识到,如果你有类似[11.5, 3.1, 3.5, 3.7]因为11.5被视为一个字符串,并且会以字典顺序排在3.x 之前 ,你需要传递自定义排序函数确保它们确实被视为浮动:

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

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

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

var max_value = Math.max(val1, val2, val3, val4, val5);
arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);

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> 

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 用我的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM