如何在数组对象中搜索属性的最大值?
可以通过两种方式搜索对象数组中属性的最大值,一种是遍历数组,另一种是使用Math.max.apply()方法。
示例 1:在此示例中,遍历数组并针对数组的每个索引比较对象的所需值。
// Array of object
var arr = [
{
a: 10,
b: 25
},
{
a: 30,
b: 5
},
{
a: 20,
b: 15
},
{
a: 50,
b: 35
},
{
a: 40,
b: 45
},
];
// Returns max value of
// attribute 'a' in array
function fun(arr){
var maxValue = Number.MIN_VALUE;
for(var i=0;imaxValue){
maxValue = arr[i].a;
}
}
return maxValue;
}
var maxValue = fun(arr);
console.log(maxValue);
输出:
50
示例 2:在此示例中,我们使用Math.max.apply()函数找到属性的最大值。它有两个参数:
- 这
- 类数组对象
句法:
Math.max.apply(thisArg, [ argsArray])
更多信息可以在 https://developer.mozilla.org/ 找到
var arr = [
{
a: 10,
b: 25
},
{
a: 30,
b: 5
},
{
a: 20,
b: 15
},
{
a: 50,
b: 35
},
{
a: 40,
b: 45
},
];
var maxValue = Math.max.apply(null,
arr.map(function(o) { return o.a; }));
console.log(maxValue);
输出:
50