I need to order a graph appropriately, considering the levels.
Assuming I have this data:
const people = [
{
'name': 'john',
'level': 0,
'connections': ['monica', 'jeffrey']
},
{
'name': 'monica',
'level': 1,
'connections': ['william']
},
{
'name': 'jeffrey',
'level': 1,
'connections': ['george']
},
{
'name': 'george',
'level': 1,
'connections': []
},
{
'name': 'william',
'level': 2,
'connections': ['rachel']
},
{
'name': 'rachel',
'level': 3,
'connections': []
}
]
How can I go about outputting the correct order in which they should be formed?
Example of correct order:
/*
[
John
- Monica
-- William
--- Rachel
- Jeffrey
-- George
]
*/
// (No need to worry about -)
I tried:
let orderCounter = 1;
people.forEach(person => {
person['order'] = person['order'] || ++orderCounter;
if (person.connections > 0)
person.connections.forEach(connection => {
const foundPerson = people.find(x => x === connection);
foundPerson['order'] = foundPerson['order'] || ++orderCounter;
});
});
I don't really enjoy having so many loops inside one another.
The question is, how can I make this more effective rather than being convoluted?