Home > Enterprise >  How to print the leaf nodes from an array of list of objects in typescript?
How to print the leaf nodes from an array of list of objects in typescript?

Time:05-21

I am new to typecript and I am having problem doing the following, I have an array and I want to print the leaf nodes only, The resulting array should look like-['002', '004', '007'], Can someone please help..Looking forward to learn, Thanks in advance !

The array-

[
        {
            Name: "A",
            HasChildren: true,
            Children: [
                {
                    Name: "002",
                    HasChildren: false,
                    Children: []
                },
                {
                    Name: "004",
                    HasChildren: false,
                    Children: []
                }
            ]
        },
        {
            Name: "007",
            HasChildren: false,
            Children: []
        }
    ]

If array is

[ {
                Name: "007",
                HasChildren: false,
                Children: []
  }
]

resulting array should be - ['007']

CodePudding user response:

What you can do is go through each element. If it does not have children, print it and continue on to its next sibling. If it does have at least one child, recursively go through each child with the same logic.

Stackblitz: https://stackblitz.com/edit/typescript-vfvyn7?file=index.ts

const elements = [
  {
    Name: 'A',
    HasChildren: true,
    Children: [
      {
        Name: '002',
        HasChildren: false,
        Children: [],
      },
      {
        Name: '004',
        HasChildren: false,
        Children: [],
      },
    ],
  },
  {
    Name: '007',
    HasChildren: false,
    Children: [],
  },
];
console.log(elements);

function printLeaves(elements: any[]) {
  for (const element of elements) {
    if (element.Children.length == 0) {
      console.log(element);
      continue;
    }
    printLeaves(element.Children);
  }
}

printLeaves(elements)
  • Related