ES6 Find the maximum number of an array of objects

前端 未结 7 1294
栀梦
栀梦 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 18:00

    You could check the amount property of both items and return the item with the greatest amount.

    let highest = shots.reduce((a, b) => a.amount > b.amount ? a : b);
    

    For same amount, you get the first object with the same amount only.

    It does not work with an empty array.

    If you like all objects with the same highest amount, you could reduce the array with with two conditions.

    let highest = shots.reduce((r, o) => {
            if (!r || o.amount > r[0].amount) return [o];
            if (o.amount === r[0].amount) r.push(o);
            return r;
        }, undefined);
    

提交回复
热议问题