Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Find the maximum number of an array of objects

I have the following data

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

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

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?

Thank you.

like image 947
Miguel Stevens Avatar asked Feb 14 '18 12:02

Miguel Stevens


1 Answers

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)
like image 103
Cristian S. Avatar answered Nov 07 '22 09:11

Cristian S.