1

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

2
  • How many objects are in child. Many or one? Commented Jun 17, 2022 at 17:33
  • there can be from 0 to unlimited Commented Jun 17, 2022 at 17:33

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

Comments

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.