获取JS中用于过滤的对象数组的最大值

Nic*_*kon 0 javascript arrays

我有一组对象,如:

var myArr = [{
    number: 5,
    shouldBeCounted: true
}, {
    number: 6,
    shouldBeCounted: true
}, {
    number: 7,
    shouldBeCounted: false
}, ...];
Run Code Online (Sandbox Code Playgroud)

如何找到设置为?的number对象的最大值?我不想使用循环,只是想知道这是否可能(或类似的东西).shouldBeCountedtrueMath.max.apply

Ale*_* T. 5

不,这是不可能的.您可以使用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);
Run Code Online (Sandbox Code Playgroud)