0

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},
                   {Name: 'PersonB', Percentage: 30},
                   {Name: 'PersonC', Percentage: 50}]
},
 {BenefitType:'IRA',
   Beneficiaries: [{Name: 'PersonA', Percentage: 15},
                   {Name: 'PersonB', Percentage: 45},
                   {Name: 'PersonC', Percentage: 40}]
}];

I would like to sum all the percentages by their Benefit Type so that 401k = 100and IRA = 100.

I have the following code, but it gives me a grand total for percentages instead of totals for each benefit type:

var myTotal = 0;

for(var i = 0; i < data.benefit_type.length; i++) {
    for(var j=0; j < data.benefit_type[i].beneficiaries.length; j++) {
        myTotal += parseInt(data.benefit_type[i].beneficiaries[j].percentage); 
        data.benefit_type[i].percent_total = myTotal;

    } 
}

What am I missing to fix this?

1

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why must you use map and reduce? Why not just reduce?
@CoryKleiser you're right, I've modified and simplified my answer based on what OP is trying to achieve

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.