There are several ways to transform an Array into a Tree using TypeScript, but one of the most effective methods is to use recursion. Here is an example implementation:
interface TreeNode {
value: any;
children?: TreeNode[];
}
function createTreeFromArray(arr: any[]): TreeNode[] {
const tree: TreeNode[] = [];
function buildTree(parent: TreeNode, children: any[]) {
for (const val of children) {
const node = { value: val } as TreeNode;
parent.children = parent.children || [];
parent.children.push(node);
if (Array.isArray(val)) {
buildTree(node, val);
}
}
}
for (const val of arr) {
const root = { value: val } as TreeNode;
tree.push(root);
if (Array.isArray(val)) {
buildTree(root, val);
}
}
return tree;
}
This implementation first creates an empty array called tree
, which will store the top-level nodes of the tree. Then, it defines a recursive function called buildTree
, which takes a parent node and an array of children as arguments. For each item in the children
array, it creates a new TreeNode
object with a value
property equal to the item's value. If the item is an array (i.e., has children), it recursively calls buildTree
with the new node as the parent and the item as the children. Finally, it adds the node to the parent
node's children
array.
The createTreeFromArray
function then loops through each item in the input array (arr
) and creates a new top-level node for each item. If the item is an array, it calls buildTree
with the new node as the parent and the item as the children. Finally, it returns the tree
array containing all of the top-level nodes.
Usage:
const arr = ['A', ['B', 'C', ['D', 'E']], 'F'];
const tree = createTreeFromArray(arr);
console.log(tree);
/* Output:
[
{ value: 'A', children: [] },
{
value: ['B', 'C', ['D', 'E']],
children: [
{ value: 'B', children: [] },
{ value: 'C', children: [] },
{
value: ['D', 'E'],
children: [
{ value: 'D', children: [] },
{ value: 'E', children: [] }
]
}
]
},
{ value: 'F', children: [] }
]
*/
Asked: 2023-07-06 20:01:27 +0000
Seen: 13 times
Last updated: Jul 06 '23