Creating a Tree out of PathStrings

I have a similar problem to this (Get a tree like structure out of path string). I tried to use the provided solution but can not get it to work in Angular.

The idea is to the separate incoming path strings (see below) and add them to an object and display them as a tree.

 pathStrings: string[] = [
    "PathA/PathA_0",
    "PathA/PathA_1",
    "PathA/PathA_2/a",
    "PathA/PathA_2/b",
    "PathA/PathA_2/c"
  ];

  let tree: Node[] = [];

    for (let i = 0; i < this.pathStrings.length; i++) {
      tree = this.addToTree(tree, this.pathStrings[i].split("/"));
    }



  addToTree(root: Node[], names: string[]) {
    let i: number = 0;
    if (names.length > 0) {
      for (i = 0; i < root.length; i++) {
        if (root[i].name == names[0]) {
          //already in tree
          break;
        }
      }
      if (i == root.length) {
        let x: Node = { name: names[0] };
        root.push(x);
      }
      root[i].children = this.addToTree(root[i].children, names.slice(1));
    }
    return root;
  }

The result is supposed to look like this:

const TREE_DATA: Node[] = [
  {
    name: "PathA",
    children: [
      { name: "PathA_0" },
      { name: "PathA_1" },
      {
        name: "PathA_2",
        children: [{ name: "a" }, { name: "b" }, { name: "c" }]
      }
    ]
  },
  {
    name: "PathB",
    children: [
      { name: "PathB_0" },
      { name: "PathB_1", children: [{ name: "a" }, { name: "b" }] },
      {
        name: "PathC_2"
      }
    ]
  },
  {
    name: "PathC",
    children: [
      { name: "PathB_0" },
      { name: "PathB_1", children: [{ name: "a" }, { name: "b" }] },
      {
        name: "PathC_2"
      }
    ]
  }
];

Here is the Stackblitz Link (https://stackblitz.com/edit/angular-h3btn5?file=src/app/tree-flat-overview-example.ts) to my intents.. Im trying for days now without success.. Thank you so much!!

Answer

In plain Javascript, you could reduce the array by using a recursive function for thesearching and assign then new child to a given node.

const
    getTree = (node, names) => {
        const name = names.shift();
        let child = (node.children ??= []).find(q => q.name === name);
        if (!child) node.children.push(child = { name });
        if (names.length) getTree(child, names);
        return node;
    },
    pathStrings = ["PathA/PathA_0", "PathA/PathA_1", "PathA/PathA_2/a", "PathA/PathA_2/b", "PathA/PathA_2/c"],
    tree = pathStrings
        .reduce((target, path) => getTree(target, path.split('/')), { children: [] })
        .children;

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }