简体   繁体   中英

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

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']

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM