I'm trying to learn recursion and I have a code that tries to extract all parent names and push them to array if they have children.
My problem is that I am able to print out all the parents but can only seem to push 2 out of 5 of them.
function printChildrenRecursive(t) {
let hasChildren = []
if (t.children.length === 0) {
return
}
t.children.forEach(child => {
if (child.children.length > 0) {
console.log(child.name)
hasChildren.push(child.name)
}
printChildrenRecursive(child)
})
return hasChildren
}
const tree = {
name: 'John',
children: [{
name: 'Jim',
children: [{
name: 'Joe',
children: [{
name: 'Lee',
children: []
}]
}]
},
{
name: 'Zoe',
children: [{
name: 'Kyle',
children: [{
name: 'Tony',
children: []
}]
},
{
name: 'Sophia',
children: [{
name: 'Thor',
children: []
}]
}
]
}
]
}
let res = printChildrenRecursive(tree)
console.log(res);
The console.log outputs
Jim
Joe
Zoe
Kyle
Sophia
But the hasChildren.push only outputs
(2) ["Jim", "Zoe"]
printChildrenRecursiveis a strange name for a function that should return an array of parents.