Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Calculate sum of values from objects insidte nested array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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. ?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading