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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With