JavaScript reduce throwing error for more than two items

前端 未结 4 1763
你的背包
你的背包 2021-01-23 12:19

I have this array:

const arr = [
  { someProp: [{ amount: 10 }]},
  { someProp: [{ amount: 12 }]},
];

and then this reduce fn:

con         


        
4条回答
  •  死守一世寂寞
    2021-01-23 13:08

    Actually you need only to return the accumulator + the new value.

    You want to begin with 0 i guess so you need to add 0 as second parameter

    const arr =
        [
          { someProp: [{ amount: 10 }]},
          { someProp: [{ amount: 12 }]},
          { someProp: [{ amount: 12 }]},
        ];
        
    const sum = arr.reduce((acc, item) => item.someProp[0].amount + acc, 0);
    
    console.log(sum);

    If you want it more spicy here with destructuring

    const arr =
        [
          { someProp: [{ amount: 10 }]},
          { someProp: [{ amount: 12 }]},
          { someProp: [{ amount: 12 }]},
        ];
        
    const sum = arr.reduce((acc, { someProp: [{ amount }] }) => amount + acc, 0);
    
    console.log(sum);

提交回复
热议问题