Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Tree Structure of Objects by Class Property

I have a tree structure of objects (JavaScript/TypeScript), all derived of the same class (T). Each object may or may not contain children of the same object (List). Therefore those children may or may not contain their own children (List), and so on...

I'm needing to sort each of these "levels" of nodes by a specific property of the object.

Currently I'm handling only each parent and their children:

                    nodes.sort((a, b) => {
                        return a.Id- b.Id;
                    });                       

                    nodes.forEach(function (node) {
                        node.children.sort((a, b) => {
                            return a.Id- b.Id;
                        });
                    });

However, I'm needing a method that will sort all children of children, children of those children, and etc. I imagine this will involve recursion, but I'm not sure the best way of handling this in terms of efficiency.

like image 243
cdalto Avatar asked Oct 20 '22 06:10

cdalto


1 Answers

a) Sort the nodes.

b) Go through each node, if the node has children, repeat step A with its children.

function sortNodesAndChildren(nodes) {
    nodes.sort();
    nodes.forEach(function (node) {
        if (nodeHasChildren(node)) {
            sortNodesAndChildren(node.children);
        }
    }
}
like image 173
MattDiamant Avatar answered Oct 22 '22 00:10

MattDiamant