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

79
Views
want to add all ages if objects were dynamic

this is persons object how can I add all ages in here if the object were dynamic. I tried to do it with recursion but not succeded any body can help , I tried to achieve it by reduce method of javascript but can't get the logic how to return value and add continuously to get result

enter code here

const persons = {
  name: "Tom",
  age: 70,
  kids: [
    {
      name: "Jerry",
      age: 40,
      kids: [
        {
          name: "Jack",
          age: 10,
          kids: [
            {
              name: "take",
              age: 10,
            },
            {
              name: "Note",
              age: 5,
            },
          ],
        },
        {
          name: "atleast",
          age: 5,
        },
      ],
    },
   
  ],
};


here is my code 

let sum = 0;
const red = (arr) => {
  sum += arr.reduce((total, b) => {
    if (b.kids) {
      red(b.kids);
    }
    return total + b.age;
  }, sum);
  console.log(sum);
};
red(persons.kids);

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

0

Here's a simple approach:

const addAges = (person) => 
  person .age + (person .kids || []) .map (addAges) .reduce ((a, b) => a + b, 0)

I think this is a bit cleaner if we destructure the input:

const addAges = ({age, kids = []}) => 
  age + kids .map (addAges) .reduce ((a, b) => a + b, 0)

And here it's still better if we extract a sum helper function, leading to a version I like:

const sum = (ns) => 
  ns .reduce ((a, b) => a + b, 0)

const addAges = ({age, kids = []}) => 
  age + sum (kids .map (addAges))

const persons = {name: "Tom", age: 70, kids: [{name: "Jerry", age: 40, kids: [{name: "Jack", age: 10, kids: [{name: "take", age: 10}, {name: "Note", age: 5}]}, {name: "atleast", age: 5}]}]}

console .log (addAges (persons))

So addAges is a recursive function we call it for each entry of our kids array, and it will return their nested sums. Then we total the results with our value to get our final result. The base case is just when there are no kids, and we will end up with only the age of our person.

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!