我有一个对象数组,如:
var myArr = [{
number: 5,
shouldBeCounted: true
}, {
number: 6,
shouldBeCounted: true
}, {
number: 7,
shouldBeCounted: false
}, ...];
如何为shouldBeCounted
设置为true
的对象找到最大true
?我不想使用循环,只是想知道Math.max.apply
(或者类似这样的东西)是否可能使用循环。
发布于 2015-05-05 05:49:13
不不可能。您可以将Math.max
与.map
一起使用,如下所示
var myArr = [{
number: 5,
shouldBeCounted: true
}, {
number: 6,
shouldBeCounted: true
}, {
number: 7,
shouldBeCounted: false
}];
var max = Math.max.apply(Math, myArr.map(function (el) {
if (el.shouldBeCounted) {
return el.number;
}
return -Infinity;
}));
console.log(max);
发布于 2015-05-05 05:53:37
使用简单的.reduce()
var myArr = [{
number: 5,
shouldBeCounted: true
}, {
number: 6,
shouldBeCounted: true
}, {
number: 7,
shouldBeCounted: false
}];
var max = myArr.reduce(function(max, current) {
return current.shouldBeCounted ? Math.max(max, current.number) : max;
}, -Infinity);
console.log(max);
哪里
myArr.reduce()
-将数组还原为单个值。接受一个包含两个参数的函数,即当前累积值和当前项(另外两个可选参数用于项的索引和原始数组)。return current.shouldBeCounted ? Math.max(max, current.number) : max;
-对于每个项目,返回当前最大值是shouldBeCounted是假的,或者当前已知最大值和当前数字之间的最大值。, -Infinit
-从-Infinity
开始。与接受的答案中的方法相比,这种方法的优点是只迭代数组一次,而.filter()
和.map()
分别循环数组一次。
发布于 2015-05-05 06:05:32
另一个较少冗长的解决方案(如果您的数字都是正数):
var max = Math.max.apply(Math, myArr.map(function(el) {
return el.number*el.shouldBeCounted;
}));
https://stackoverflow.com/questions/30054677
复制