我有以下数据
shots = [
{id: 1, amount: 2},
{id: 2, amount: 4}
]
Now I'm trying to get the object which has the highest amount
我尝试过使用reduce,如下所示
let highest = shots.reduce((max, shot) => {
return shot.amount > max ? shot : max, 0
});
但我总是得到最低的数字。 知道我可能会错过什么吗?
谢谢。
最佳答案
更清洁的 2 行解决方案:)
const amounts = shots.map((a) => a.amount)
const highestAmount = Math.max(...amounts);
更新
上面的代码将返回最高金额。如果你想获取包含它的对象,你将面临许多对象包含最高值的可能性。所以你需要过滤器
。
const highestShots = shots.filter(shot => shot.amount === highestAmount)
关于javascript - ES6 求对象数组的最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48786855/