简体   繁体   English

在javascript数组中查找最小值?

[英]Finding smallest value in a javascript array?

Say I have an array like the following: 假设我有一个如下所示的数组:

var myArray = new Array();
myArray[0] = {ValueA: 10, ValueB:900};
myArray[1] = {ValueA: 50, ValueB:190};

How would I select the element that has the smallest value for ValueA ? 如何选择ValueA值最小的元素?

I've used the following to get the max of arrays of numbers before: 我之前使用以下内容来获取最大数字数组:

var largest = Math.max.apply(Math, myArray);

but i'm not sure how this method could be used to find the max/min of an array of objects. 但我不确定如何使用此方法来查找对象数组的最大/最小值。 Suggestions? 建议?

You could sort the array using a custom function then get the first and last members, eg 您可以使用自定义函数对数组进行排序,然后获取第一个和最后一个成员,例如

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

Smallest: 最小:

myArray[0].ValueA;

Biggest: 最大:

myArray[myArray.length - 1].ValueA;

If you don't want to modify the order of your array, copy it first (the objects wont be copied, they'll just be referenced). 如果您不想修改数组的顺序,请先复制它(不会复制对象,只会引用它们)。

var myArray = new Array();
myArray[0] = {ValueA: 10, ValueB:900};
myArray[1] = {ValueA: 50, ValueB:190};
myArray[2] = {ValueA: 25, ValueB:160};
myArray[3] = {ValueA: 5, ValueB:10};

var copy = myArray.slice();
alert(copy.length);

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

alert(copy[0].ValueA); // 5
alert(copy[copy.length - 1].ValueA); // 50
Math.min.apply(Math,myArray.map(function(x){return x.ValueA;}));

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

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