ES6 Find the maximum number of an array of objects

前端 未结 7 1295
栀梦
栀梦 2021-01-14 17:27

I have the following data

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

Now I\'m trying to get the object which

7条回答
  •  悲&欢浪女
    2021-01-14 17:48

    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;
    

    Edit:

    A clean short one liner would look something like so:

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

提交回复
热议问题