Ask Your Question
2

What is the most effective method to transform an Array into a Tree using TypeScript?

asked 2023-07-06 20:01:27 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-06 20:14:02 +0000

david gravatar image

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: [] }
]
*/
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-06 20:01:27 +0000

Seen: 13 times

Last updated: Jul 06 '23