Reputation: 524
I'm trying to get the Sum of the nested array. The array structure is like this:
const arr = [
{ question: 'A', parentId: 1, weightage: 10, child: [] },
{
question: 'B',
parentId: 4,
weightage: 0,
child: [{ id: 4, sub_question: 'X', weightage: 55 }]
},
{ question: 'C', parentId: 5, weightage: 20, child: [] }
]
Here You can see a Question and then a Child array with SubQuestions. And both have a key named weightage. I want to calculate all the weightage values into a sum.
I'm using this approach
const sum = (value, key) => {
if (!value || typeof value !== 'object') return 0
if (Array.isArray(value)) return value.reduce((t, o) => t + sum(o, key), 0)
if (key in value) return value[key]
return sum(Object.values(value), key)
}
const weightage = sum(arr, 'weightage')
Here I can get the value of weightage from Questions but not from Child Array. Like in the above example of arr. I'm getting sum = 30, but that should be equal to 85, How can I fix this. ?
Upvotes: 1
Views: 105
Reputation: 386560
You could take a recursive approach.
const
sum = (array = [], key) => array.reduce(
(total, object) => total + object[key] + sum(object.child, key),
0
),
data = [{ question: 'A', parentId: 1, weightage: 10, child: [] }, { question: 'B', parentId: 4, weightage: 0, child: [{ id: 4, sub_question: 'X', weightage: 55 }] }, { question: 'C', parentId: 5, weightage: 20, child: [] }],
result = sum(data, 'weightage');
console.log(result)
Upvotes: 5