Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda