What is the best way to output the leaf nodes from an array of object lists in TypeScript?

Having trouble with TypeScript, specifically working with arrays and filtering out leaf nodes. I want to print only the leaf nodes in the array, resulting in ['002', '004', '007']. Can someone please assist me? Excited to learn! Thank you in advance!

Here is the initial array structure:

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

If the array is:

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

The resulting array should be: ['007']

Answer №1

If you want to display all the leaf elements in a structured data with nested children, you can follow this approach. Start by checking each element - if it has no children, print it out and move on to the next sibling. If it does have children, recursively go through each child using the same logic.

You can try implementing this solution in your TypeScript project using 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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

Is there a way to display a PowerPoint presentation preview within an Angular application without utilizing the ngx-doc-viewer plugin?

Is it possible to display a PowerPoint preview in an Angular application? I am looking to show PowerPoint presentations stored in a server location. I prefer not to use ngx-doc-viewer as it appends "https://docs.google.com/gview+fileurl" instead of just " ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

Creating form inputs dynamically in HTML and then sending them to a PHP script programmatically

On my webpage, users can click a button to add new form inputs as needed. However, I'm running into an issue trying to access these new inputs in the PHP file where I submit the data. Here is the code snippet for the button within the form on the pag ...

When I attempt to click on the Cancel button, the database row remains undeleted

After a user clicks on the "Cancel" button, I want to reset the source and remove the iframe to prevent the file from being uploaded to the server. This function is currently working as intended. However, I am facing an issue where even after clicking on ...

Can general principles be applied to determine which script is the most efficient and will load the quickest?

Is there a way to determine which script is optimal and will load faster when there are multiple ways to write scripts that achieve the same outcome? ...

What is causing the undefined value to appear?

I'm puzzled as to why the term "element" is coming up as undefined. Even after running debug, I couldn't pinpoint the cause of this issue. Does anyone have any insights on what might be going wrong here? Below is the snippet of my code: const ...

Create a pinia state by defining it through an interface without the need to manually list out each property

Exploring the implementation of state management (pinia) within a single-page application is my current task. We are utilizing typescript, and I am inquiring about whether there exists a method to define a state based on an interface without needing to ret ...

Is it possible to modify the timezone when using MuiPickersUtilsProvider?

I'm looking to update the timezone based on the user's input selection. Currently, I've set a default timezone using moment.tz.setDefault("user timezone") and passed moment and MomentUtils as props in the MuiPickersUtilsProvider. However, th ...

Sorting a 2D array in Javascript based on numerical values

I've come across a few similar posts regarding this issue, but none have provided solutions that work for my specific situation. I'm feeling lost on how to solve this problem (like Sort a 2D array by the second value) Let me explain the challeng ...

Mastering the art of simultaneously running multiple animations

Utilizing two functions to apply a Fade In/Fade Out effect on an element. Confident in the functionality of both functions, as testing them sequentially in the Console proves their effectiveness. However, executing: fadeIn() fadeOut() seems to result in ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

Setting up the InMemoryCache in Vue ApolloConfiguring the InMemoryCache

I've set up vue-apollo following the instructions in the apollo.config.js file from this guide: (I'm using VSCode). Now, I want to configure the InMemoryCache to exclude the typeName (addTypename: false) like it's explained here: https://w ...

Function with defer that calls itself repeatedly

I am attempting to utilize a recursive function where each function runs only after the previous one has completed. This is the code I have written: var service = ['users', 'news'], lastSync = { 'users' : ...

Object-oriented programming in JavaScript allows for the passing of variables to a parent class using $

I am attempting to transfer variables from an XML file to the parent class in JavaScript. The code follows Object-Oriented Programming principles, with a class named "example" and a method called getData(). The issue I'm encountering is that the AJAX ...

Issues with calculating SUM in MySQL within a Node.js Express application using EJS template

I am currently working on developing a dashboard for my Node.js project. The aim is to calculate the sum of certain values for an overview. While the SELECT statement works fine in my MySQL database, when I incorporate it into my Node project, I do not rec ...

Tips for styling my date using MomentJS

I am currently using moment.js for displaying dates in my application. The date format is determined based on the locale stored in the variable clientLanguage. I have tried various approaches, including the following: moment(myISODate).locale(clientLang ...

Tips for avoiding the <p> and <br> elements while using a ContentEditable div

Upon pressing the enter key, the editor automatically inserts paragraph and page break elements. What are some strategies to avoid these unwanted elements in the editor? ...

Flag form field as invalid in AngularJS

Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message? Here's the setup of my app: I have a model 'client' with a controller Accounts.controller(&ap ...

Utilizing a personalized directive within a ionic popup

I am currently using the ion-textarea autosize directive: import { Directive, HostListener, ElementRef } from '@angular/core'; @Directive({ selector: 'ion-textarea[autosize]' }) export class AutoResizeTextareaDirective { readonly ...