S
S
sugadu2016-09-01 21:50:38
JavaScript
sugadu, 2016-09-01 21:50:38

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}
]

Need to make a hierarchy based on levels. For the current example, it will be like this:
{
    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
                }
            ]
        }
    ]
}

Help me write an algorithm.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Gromov, 2016-09-02
@sugadu

https://jsfiddle.net/3y4ewh20

A
Andrew, 2016-09-01
@OLS

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 question

Ask a Question

731 491 924 answers to any question