JavaScript reduce throwing error for more than two items

前端 未结 4 1725
你的背包
你的背包 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 12:58

    Following @Pointy answer, this is how you can get it working with any number of elements:

    const sum = arr.reduce((prev, curr) => prev + curr.someProp[0].amount, 0);
    

    prev is always the previously returned element, so you can safely use it as a number (and since you're just summing it, you can use 0 as default, so the first time reduce is invoked the value of prev will be 0)

提交回复
热议问题