I have the following data
shots = [
{id: 1, amount: 2},
{id: 2, amount: 4}
]
Now I\'m trying to get the object which
Sadly enough most answers here do not properly consider all cases
To properly handle negative values, you would have to seed with -Infinity
Secondly compare the largest value of that point with the new value
You'd get the following:
highest = shots.reduce((max, current) => current.amount >= max.amount ? current : max, {amount: -Infinity})
You can test this with
shots = [
{id: 1, amount: -2},
{id: 2, amount: -4},
{id: 3, amount: -4},
{id: 4, amount: -5},
]
highest = shots.reduce((max, current) => current.amount >= max.amount ? current : max, {amount: -Infinity}) // Returns id 1, amount -2
shots = [
{id: 1, amount: 2},
{id: 2, amount: 4},
{id: 3, amount: 4},
{id: 4, amount: 5},
]
highest = shots.reduce((max, current) => current.amount > max.amount ? current : max, {amount: -Infinity}) // Returns id 4 amount 5
Note that if the array is empty, you will get a value of {amount: -Infinity}
as a result, so you might want to handle the case where shots.length === 0
before the reduce