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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.