如何在JavaScript中对两个数组数据求和

时间:2018-09-07 04:14:53

标签: javascript

如何将第一个数组的数据与其中的数组数据求和?

one

代码

这是我当前的代码,仅在第一个数组上工作

calculateTotal: function(){
  var sum=0;
  for(var i=0;i<this.accounts.length;i++){
     sum += this.accounts[i].balance;
  }
  return sum;
},

我应该如何更改此代码以获得我想要的结果?

4 个答案:

答案 0 :(得分:2)

不仅需要balance属性,还需要在balance数组中添加每个payments属性。您可以使用reduce非常简洁地进行此操作,将外部balance传递为累加器的初始值:

const obj = {
  accounts: [{
    balance: 150000,
    payments: [{
        balance: 100000,
      },
      {
        balance: -200000,
      }
    ]
  }]
};
const total = obj.accounts.reduce((a, { balance, payments }) => (
  a + payments.reduce((accum, { balance }) => accum + balance, balance)
), 0);
console.log(total);

或者,以对象方法的形式:

const obj = {
  calculateTotal() {
    return obj.accounts.reduce((a, { balance, payments }) => (
      a + payments.reduce((accum, { balance }) => accum + balance, balance)
    ), 0)
  },
  accounts: [{
    balance: 150000,
    payments: [{
        balance: 100000,
      },
      {
        balance: -200000,
      }
    ]
  }]
};
console.log(obj.calculateTotal());

答案 1 :(得分:1)

您可以试试吗?

 calculateTotal: function(){
      var sum=0;
      for(var i=0;i<this.accounts.length;i++){
         sum += this.accounts[i].balance;
         // iterate over payments sub array in each account and add balance into the sum
         for(var j=0;j<this.accounts[i].payments.length;j++){
             sum += this.accounts[i].payments[j].balance;
         }
      }
      return sum;
    },

答案 2 :(得分:1)

我只是尝试了一种更通用的解决方案类型,以计算一个给定的键,该键可以嵌套到任意数量的数组或对象中。

summarize = (obj, sum_key) => {
  var sum = 0;
  for ( key in obj ) {
    if (key == sum_key) {
      sum += obj[key];
    } else if (typeof obj[key] == 'object' && obj[key]) {
      sum += summarize(obj[key]);
    }
  }
  return sum;
};

现在,您可以通过以下方式获得所需的金额:

summarize(data, 'balance');

答案 3 :(得分:0)

在这种情况下使用reduce

  sumOfPaymentBalance = accounts.payments.reduce((sum,currentValue)=> 
                          (sum+currentValue.balance),0);
    mainBalance = accounts.reduce(sum,paymentValue=>(sum,paymentValue.balance),0);
    sumOfPaymentBalance += mainBalance;
    console.log(sumOfBalance);