ES6查找对象数组的最大数量 [英] ES6 Find the maximum number of an array of objects

查看:666
本文介绍了ES6查找对象数组的最大数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据

shots = [
    {id: 1, amount: 2},
    {id: 2, amount: 4}
]




现在我正在尝试获取数量最高的对象

Now I'm trying to get the object which has the highest amount

我尝试使用reduce,如下所示

I've tried using reduce like follows

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

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

But I'm always getting the lowest number. Any idea what I might be missing?

谢谢。

推荐答案

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

There are two problems here, the first is that a reduce needs a return value. the second is you're comparing a number with an object.

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

Therefore, I think you need something like this:

// 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;



编辑:



干净短的一个班轮看起来像这样:

A clean short one liner would look something like so:

const highest = shots.sort((a, b) => b.amount - a.amount)[0]

这篇关于ES6查找对象数组的最大数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆