比较对象的JavaScript Array获取最小/最大 [英] Compare JavaScript Array of Objects to Get Min / Max

查看:141
本文介绍了比较对象的JavaScript Array获取最小/最大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的数组,我想对这些对象的特定对象属性进行比较。这里是我的阵列 -

I have an array of objects and I want to compare those objects on a specific object property. Here's my array -

var myArray = 
[
{"ID": 1, "Cost": 200},
{"ID": 2, "Cost": 1000},
{"ID": 3, "Cost": 50},
{"ID": 4, "Cost": 500}
]

我想在零上的成本明确和得到分钟,最大值。我知道我可以抓住的成本值,并把他们关到一个JavaScript数组,然后运行快速的JavaScript最大值/最小值

但有一个简单的方法绕过中间的步阵和去关闭对象的属性(在这种情况下,成本),这样做直接?

However is there an easier way to do this by bypassing the array step in the middle and going off the objects properties (in this case "Cost") directly?

推荐答案

的最快方法,在这种情况下,通过所有的元素循环,并将其与最高/最低值,那么远。

The fastest way, in this case, is looping through all elements, and compare it to the highest/lowest value, so far.

(创建一个数组,数组调用方法是矫枉过正这个简单的操作)。

 // There's no real number bigger than plus Infinity
var lowest = Number.POSITIVE_INFINITY;
var highest = Number.NEGATIVE_INFINITY;
var tmp;
for (var i=myArray.length-1; i>=0; i--) {
    tmp = myArray[i].Cost;
    if (tmp < lowest) lowest = tmp;
    if (tmp > highest) highest = tmp;
}
console.log(highest, lowest);

这篇关于比较对象的JavaScript Array获取最小/最大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆