Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!