I'm working with an array like the below:
arr = [{
item: "Subject",
id: "16",
parent_id: ""
},
{
item: "Math",
id: "17",
parent_id: "16"
},
{
item: "Geology",
id: "988",
parent_id: "208"
},
{
item: "Biology",
id: "844",
parent_id: "208"
},
{
item: "Botany",
id: "594",
parent_id: "844"
},
{
item: "Science",
id: "208",
parent_id: "16"
}
]
I'm wanting to sort them so and print them out so that they display like this, grouping them and showing their parentage within the hierarchy as indentations:
Subject
Math
Science
Geology
Biology
Botany
I'm fairly stumped on how to accomplish this. I am ultimately wanting to iterate through the array only once, but I get stuck when I realize that a parent item may come after its child. Any help is greatly appreciated.
Edit: eliminated the duplicate item
To sort an array by an attribute of its elements...
Then a little recursion to walk the tree...
Putting it all together...
Note, if you have duplicate parents, you will get duplicate branches (hint: your example array has a duplicate "Science" node).
Also note, sorting the array ahead of time doesn't really matter for the tree, since it is a hierarchy, I just added it to show how to do it. You'd probably just sort each set of children like so...
And you get this...