Answer the question
In order to leave comments, you need to log in
How to convert a linear structure to a hierarchical one?
There is a simple linear array. Example:
[
{ level: 0},
{ level: 1},
{ level: 2},
{ level: 1},
{ level: 2},
{ level: 1},
{ level: 2},
{ level: 3},
{ level: 3},
{ level: 4},
{ level: 2}
]
{
level: 0,
content: [
{
level: 1,
content: [
{
level: 2
}
]
},
{
level: 1,
content: [
{
level: 2
}
]
},
{
level: 1,
content: [
{
level: 2,
content: [
{
level: 3
},
{
level: 3,
content: [
{
level: 4
}
]
}
]
},
{
level: 2
}
]
}
]
}
Answer the question
In order to leave comments, you need to log in
I would suggest recursion. Everything that is returned by deeper recursion calls, as well as single (without children) nodes of the current level, we hook up to one level. As soon as we met a level higher than the current one in the linear array, we complete the recursive procedure and feed the resulting array as the result of the call (it will be a node for a higher-level array).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question