Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

83
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda