I have an array of nodes (Node[]
) where node is described as following
export interface Node {
id:number;
value:any;
parent:number|null|undefined|false;
}
I want to convert it to a nested array of tree-nodes (TreeNode[]
) where
class TreeNode {
private _id:Node['id'];
private _value:Node['value'];
private _parent:Node['parent'];
private _children:TreeNode[] = [];
/* some other attributes */
constructor(node:Node, children:TreeNode[]){
this._id = node.id;
this._value = node.value;
this._parent = node.parent;
this.children = children; // special setter not a mistake
}
/* Some other suff here */
In my Tree root I have the following function to deal with conversion
// note before this all items in array having parent `null|undefined|false` are replaced with `-1` as all ids are positive
parseTree(array:Node[], id:Node['parent']=-1):TreeNode[] {
let tree:TreeNode[] = [];
array.forEach((item, index) => {
if (item.parent !== id)
return;
tree.push(new TreeNode(item, this.parseTree(array, item.id)));
});
return tree;
};
this works but the problem is, the larger the array the longer it takes to execute. It's arounde N² complexity as it loops through all the items again and again. I tried removing the checked items this way
array.splice(index, 1);
tree.push(new TreeNode(item, this.parseTree(array, item.id)));
but it crashes. How can I optimize this ?