I am working with a tree structure of folders that have properties such as id, parent_id, and name. Currently, this tree is stored in an unsorted array.
Each element in my array looks like this:
var obj = { id: 1, parent_id: null, name: "Folder" }
My goal is to sort this array in order to display the folder hierarchy in a structured manner, like:
Folder1
Sub_folder1
Sub_sub_folder1
Sub_folder2
Sub_sub_folder2
And so on... I am trying to achieve this without using recursion but I am facing challenges in doing it effectively.
Below are some attempts I have made. One approach involved adding an artificial field representing the number of each folder in the collection, however, this method did not produce the desired outcome:
var sort = function(list) {
var f_map = {};
var sorting_index = 1;
var tree = angular.copy(list);
for(var i = 0; i < tree.length; i++) {
var node = tree[i];
f_map[ node.id ]= { index: i, children: [] };
if (node.parent_id) {
f_map[ node.parent_id ].children.push( node.id );
};
var idx = 0;
var visited = {};
for(var key in f_map) {
var index = f_map[key].index;
var node = tree[index];
if (!visited[node.id]) {
node.nuid = idx++;
} else {
visited[node.id] = true;
};
if (f_map[key].children.length) {
var children = f_map[key].children;
for(var i = 0; i < children.length; i++) {
var child_id = children[i];
var child_idx = f_map[child_id].index;
var child = tree[child_idx];
child.nuid = idx++;
visited[child.id] = true;
};
};
};
tree.sort(function(left, right) {
return left.nuid - right.nuid;
});
return tree;
};