ES6 Find the maximum number of an array of objects

前端 未结 7 1288
栀梦
栀梦 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:44

    There are couple of mistakes

    • return shot.amount instead of shot
    • simply return the value after comparison

    Finally

    shots.reduce((max, shot) => 
        shot.amount > max ? shot.amount : max, 0);
    

    Demo

    var shots = [
        {id: 1, amount: 2},
        {id: 2, amount: 4}
    ];
    var output = shots.reduce((max, shot) => 
        shot.amount > max ? shot.amount : max, 0);
    console.log( output );

    Edit

    If the entire object has to be returned, then initializer should be an object with amount property

    var shots = [
        {id: 1, amount: 2},
        {id: 2, amount: 4} ]; 
    var output = shots.reduce((max, shot) => 
        shot.amount > max.amount ? shot : max , {amount:0}); 
    console.log( output );
    

提交回复
热议问题