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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With