Reputation: 7138
How can I sum data of my first array with data of array in it?
this is my current code which is working on first array only
calculateTotal: function(){
var sum=0;
for(var i=0;i<this.accounts.length;i++){
sum += this.accounts[i].balance;
}
return sum;
},
What should I change in this code to get the result i want?
Upvotes: 0
Views: 2593
Reputation: 429
I just tried making a more generic type of solution to count a given key which can be nested into as many arrays or objects as you wish.
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;
};
Now you can get the required sum with:
summarize(data, 'balance');
Upvotes: 0
Reputation: 2087
Use reduce
for this case
sumOfPaymentBalance = accounts.payments.reduce((sum,currentValue)=>
(sum+currentValue.balance),0);
mainBalance = accounts.reduce(sum,paymentValue=>(sum,paymentValue.balance),0);
sumOfPaymentBalance += mainBalance;
console.log(sumOfBalance);
Upvotes: 0
Reputation: 371193
You need not only the balance
property, but you also need to add every balance
property in the payments
array. You can do this very concisely with reduce
, passing in the outer balance
as the initial value of the accumulator:
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);
Or, in object method form:
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());
Upvotes: 2
Reputation: 802
Can you try this?
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;
},
Upvotes: 1