ES6 Find the maximum number of an array of objects

前端 未结 7 1296
栀梦
栀梦 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:04

    Sadly enough most answers here do not properly consider all cases

    1. The seed value is off
    2. The comparison is going between different types

    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

提交回复
热议问题