Home > database >  Recursively nest elements deeper with Angular TypeScript
Recursively nest elements deeper with Angular TypeScript

Time:06-08

I have the following array const tokens: string[] = ['A', 'B', 'C'] and I want to recursively nest them as child of the previous element like this:

[
    {
        name: "A",
        children: [
            {
                name: "B",
                children: [
                    {
                        name: "C",
                        children: null
                    }
                ]
            }
        ]
    }
]

This is my current approach, however, I´m currently running into a RangeError: Maximum call stack size exceeded:

method.ts

  private initNode(tokens: string[]): Node {
    let node: node = null!;

    if (tokens && tokens.length > 0) {       // stop if all tokens were used
      const token: string = tokens[0];
      tokens = tokens.splice(0, 1);          // remove the current token from the array

      node = {
        name: token,
        children: [this.initNodes(tokens)]   // set the upcoming node as child (null if all tokens are empty)
      };
    }

    return node;
  }

Does somebody know what I'm missing here?

CodePudding user response:

splice return the REMOVED items, not the remaining items. You don't want to assign the return value of splice back to tokens, but you can assign it to token instead.

i.e.

const token: string = tokens.splice(0,1)[0];
//no need to assign tokens, it is modified in-place

Or you can simply use reduceRight, no need to write a recursive function.

const output = ["A", "B", "C"].reduceRight((acc,cur)=>{
  return {name:cur,children:[acc]};
},null);

console.log([output]);

  • Related