JavaScript reduce throwing error for more than two items

前端 未结 4 1759
你的背包
你的背包 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:17

    This is an alternative solution... Using Array.filter().

    const arr = [{
        someProp: [{
          amount: 10
        }]
      },
      {
        someProp: [{
          amount: 12
        }]
      },
      {
        someProp: [{
          amount: -231
        }]
      },
      {
        someProp: [{
          amount: 21265
        }]
      },
      {
        someProp: [{
          amount: 1239
        }]
      },
      {
        someProp: [{
          amount: -6
        }]
      },
    ];
    const sum = arr.filter((val, index) => {
      if (index > 0) {
        arr[index].someProp[0].amount = parseInt(val.someProp[0].amount) + parseInt(arr[index - 1].someProp[0].amount);
      }
      return index == arr.length - 1;
    })[0].someProp[0].amount;
    
    console.log(sum);

提交回复
热议问题