Reputation: 111
I am using the jqtree plugin to generate a treeview. Now I want to sort the tree for every node via the label.
The plugin comes without a sort function so I think I need to sort it before I load the data into it.
This is my data to sort.
[
{
"label": "A label",
"id": "201",
"children": [
{
"label": "C Label",
"id": "40773",
"children": [
{
"label": "F label",
"id": "222460",
"children": []
},
{
"label": "C label",
"id": "222469",
"children": []
},
{
"label": "X label",
"id": "27512",
"children": [
{
"label": "F label",
"id": "143546",
"children": []
},
{
"label": "D label",
"id": "141341",
"children": [
{
"label": "G label",
"id": "222456",
"children": []
},
{
"label": "L label",
"id": "222457",
"children": []
},
{
"label": "x label",
"id": "222443",
"children": [
{
"label": "Z label",
"id": "222447",
"children": []
},
{
"label": "A label",
"id": "222446",
"children": []
}
]
},
{
"label": "L label",
"id": "222455",
"children": []
}
]
},
{
"label": "A label",
"id": "143547",
"children": [
{
"label": "B label",
"id": "222458",
"children": []
}
]
},
{
"label": "R label",
"id": "143548",
"children": []
}
]
}
]
}
]
}
]
Many thanks for any suggestions.
Upvotes: 0
Views: 345
Reputation: 2098
You can use a recursive function that iterates through your tree and any sort of sorting algorithm to sort them.
recursiveSortByLabel(arr); //arr = the array with your tree data
function recursiveSortByLabel(obj){
if(obj.length > 0){
for(var i in obj){
if(obj[i].children.length > 0)
recursiveSortByLabel(obj[i].children);
sortAlgorithm(obj); //any sorting algorithm
}
}
}
In this fiddle i did it with the rather unefficient but easy to implement bubblesort algorithm. It logs the result to the console for inspectation.
Upvotes: 2