ES6查找对象数组的最大数量

Mig*_*ens 0 javascript ecmascript-6

我有以下数据

shots = [
    {id: 1, amount: 2},
    {id: 2, amount: 4}
]
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试获得具有最高金额的对象

我尝试过使用如下的reduce

let highest = shots.reduce((max, shot) => {
    return shot.amount > max ? shot : max, 0
});
Run Code Online (Sandbox Code Playgroud)

但我总是得到最低的数字.知道我可能会缺少什么吗?

谢谢.

Cri*_* S. 9

清洁2线解决方案:)

const amounts = shots.map((a) => a.amount)
const highestAmount = Math.max(...amounts);
Run Code Online (Sandbox Code Playgroud)

更新

上面的代码将返回最高金额.如果要获取包含它的对象,您将面临许多对象包含最高值的可能性.所以你需要filter.

const highestShots = shots.filter(shot => shot.amount === highestAmount)
Run Code Online (Sandbox Code Playgroud)


sca*_*ood 7

这里有两个问题,第一个是reduce需要返回值.第二个是你将一个数字与一个对象进行比较.

因此,我认为你需要这样的东西:

// This will return the object with the highest amount.
let highest = shots.reduce((max, shot) => {
    return shot.amount >= max.amount ? shot : max;
}, {
    // The assumption here is that no amount is lower than a Double-precision float can go.
    amount: Number.MIN_SAFE_INTEGER
});

// So, we can convert the object to the amount like so:
highest = highest.amount;
Run Code Online (Sandbox Code Playgroud)

编辑:

干净的短衬里看起来像这样:

const highest = shots.sort((a, b) => b.amount - a.amount)[0]
Run Code Online (Sandbox Code Playgroud)

  • @RogierSlag - 这次谈话结束了我的一天,谢谢!希望我现在能得到它! (2认同)