javascript - ES6 求对象数组的最大数量

标签 javascript ecmascript-6

我有以下数据

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/

相关文章:

javascript - 如何用连字符定义 javascript 变量?

javascript - 有没有更优雅的 "fake"类继承方式?

javascript - 增加JS数组中的Object键

javascript - Angular 5 : Build json from values

javascript - 如何在 NumberFormat 中获取小数点后的数字?

javascript - 在 div 中显示链接名称并更改背景图片

javascript - 无法读取 null 的属性 'id' - JS 错误

javascript - 使用 Vanilla JS 重新排序选择选项列表

javascript - 如何将父字段名称添加到json对象中新添加的行

javascript - 不确定如何将方法定义转换为 ES6