This question builds on many similar ones like Construct hierarchy tree from flat list with parent field?
However the twist is that there is no parent id. e.g.
[
{id: 1, depth: 1, ...},
{id: 2, depth: 2, ...},
{id: 3, depth: 3, ...},
{id: 4, depth: 2, ...},
{id: 5, depth: 1, ...},
{id: 6, depth: 2, ...},
{id: 7, depth: 2, ...},
{id: 8, depth: 1, ...},
{id: 9, depth: 2, ...},
{id: 10, depth: 3, ...},
{id: 11, depth: 3, ...},
]
What is a performant way to construct the following tree?
Note that the children always come after the parent i.e. one can see the tree from the depth
value. For example, id 2
is a child of id 1
since its depth is 2 and id 1
has a depth of 1. id 3
is a child of id 2
since id 3
has a depth of 3. id 4
is a child of id 1
not id 3
because id 4
has a depth of 2 (a step up) from id 3
's depth of 3
\\tree digram
1
2
3
4
5
6
7
8
9
10
11
Should have values like
[
{id:1, depth:1, children: [
{id: 2, depth: 2, children: [...]},
...
]},
{id:5, depth:1, children: [...]},
{id:6, depth:1, children: [...]},
]