Skip to content Skip to sidebar Skip to footer

Sum Nested Array

I have an array within an array of objects and I want to sum the values within the nested array. [{BenefitType:'401k', Beneficiaries: [{Name: 'PersonA', Percentage: 20},

Solution 1:

You can use .forEach() to iterate through all objects and .reduce() to sum inner arrays:

let array = [{BenefitType:'401k',
   Beneficiaries: [{Name: 'PersonA', Percentage: 20},
                   {Name: 'PersonB', Percentage: 30},
                   {Name: 'PersonC', Percentage: 50}]
},
 {BenefitType:'IRA',
   Beneficiaries: [{Name: 'PersonA', Percentage: 15},
                   {Name: 'PersonB', Percentage: 45},
                   {Name: 'PersonC', Percentage: 40}]
}];


array.forEach(x => x.TotalPercentage = x.Beneficiaries.reduce((val, cur) => val + cur.Percentage, 0));

console.log(array);

EDIT:

To fix your code with double for loop you should set your myTotal variable to zero when you leave inner loop:

for(var i = 0; i < data.benefit_type.length; i++) {
    for(var j=0; j < data.benefit_type[i].Beneficiaries.length; j++) {
        myTotal += data.benefit_type[i].Beneficiaries[j].Percentage; 
        data.benefit_type[i].percent_total = myTotal;
    }
    myTotal = 0;
}

Post a Comment for "Sum Nested Array"