Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursively nest elements deeper with Angular TypeScript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading