Only first level of nesting works. Deeper levels don't work. Please help me out. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

13th Jul 2021, 3:15 AM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
6 Answers
+ 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...
13th Jul 2021, 4:16 AM
visph
visph - avatar
+ 3
visph hello again. I'm here with yet another problem.
13th Jul 2021, 3:15 AM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
+ 2
visph that's exactly what I wanted 😁😁😁😁😁.
13th Jul 2021, 2:33 PM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
+ 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
13th Jul 2021, 2:34 PM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
+ 2
visph Aha yes!!! Thanks, man😊😊😊😊
13th Jul 2021, 8:18 PM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
+ 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 ;)
13th Jul 2021, 6:45 PM
visph
visph - avatar