+ 2
Only first level of nesting works. Deeper levels don't work. Please help me out.
Finding a child node recursively https://code.sololearn.com/ca179a6A18A2/?ref=app
6 odpowiedzi
+ 2
not sure of what you're trying to achieve, and what I can assume...
assuming item searched can be value of any key, and value could be not unique in the tree:
function find(tree, item) {
return Object.values(tree).includes(item) ?
[ tree
] :
tree.children.reduce((a,o) => {
var f = find(o, item);
if (f.length) a.push(...f);
return a;
}, []);
}
return list of less deep tree(s) where item is found...
+ 3
visph hello again. I'm here with yet another problem.
+ 2
visph that's exactly what I wanted 😁😁😁😁😁.
+ 2
visph but I don't understand the code. Why did you declare the variable f? And how did you know that the value for the f will be an array? I'm confused
+ 2
visph Aha yes!!! Thanks, man😊😊😊😊
+ 1
the f variable is here to store the result array of nested calls to find function, before pushing its content to accumulator...
I know that the result value of find() is necessarly an array, because I choose by design to always return an array: either by returning [ tree ] (wrapped in an array), or tree.children.reduce() with an array as accumulator ;)