Skip to content
Advertisement

Find all descendants in array

At first look it was a simple task, but when I tried to solve it I became confused.

I have PHP array, where keys are top parent IDs, values are child IDs. Some child IDs have their own children. That children may have own children and so on. My goal is to get a new array, where all top parent IDs have all their descendants at all levels (children, grandchildren, great grandchildren and so on).

JavaScript

My attempt was next:

JavaScript

But this function doesn’t find all descendants and it seems there should be recursion, but I can’t imagine how to write it. In general I have written different functions with recursion in the past, but in this case I broken my mind )

Advertisement

Answer

You can use a stack or recursion, then explore the structure depth-first:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement