ES6 Find the maximum number of an array of objects

前端 未结 7 1285
栀梦
栀梦 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:58

    Cleaner 2 lines solution :)

    const amounts = shots.map((a) => a.amount)
    const highestAmount = Math.max(...amounts);
    

    Update

    Code above will return the highest amount. If you want to get the object that contains it, you will face the posibility that many objects contain the highest value. So you will need filter.

    const highestShots = shots.filter(shot => shot.amount === highestAmount)
    

提交回复
热议问题