I have data with a one to many relationship in the same array. The organization is established by level. An element's parent is always one level higher than itself and is referenced by parentId.
How would you get a multi level array from this array? The elements with the highest level would be the main array, with their children as subarray in javascript?
[{
_id: 100,
level: 3,
parentId: null,
},
{
_id: 101,
level: 2,
parentId: 100,
},
{
_id: 102,
level: 2,
parentId: 100,
},
{
_id: 103,
level: 2,
parentId: 100,
},
{
_id: 104,
level: 1,
parentId: 101,
},
{
_id: 105,
level: 1,
parentId: 102,
},
{
_id: 106,
level: 1,
parentId: 101,
},
{
_id: 107,
level: 1,
parentId: 103,
},
{
_id: 108,
level: 1,
parentId: 102,
},
{
_id: 109,
level: 1,
parentId: 103,
}]
Expected output would be
100
|
------------------------------------
| | |
101 102 103
------- ------ ------
| | | | | |
104 106 105 108 107 109
Thanks