Sort through the current file structure and extract the paths leading to the final destinations

I have a unique file structure representation which includes parents and children in a tree-like format

interface FileTreeProps {
  name: string;
  isMat?: boolean;
  children?: FileTreeProps[];
}

Following user input and query submission, I am looking to filter the tree so that only nodes with the type isMat at the endpoints are displayed. The initial parent folders will never have isMat = true. Any suggestions on how to approach this filtering task?

To aid in this process, I already possess the script for comparing two strings for similarity and would like to only include those children where the similarity exceeds 0.25;

An example of a standard file layout (nodes denoted by paint brushes represent the isMat nodes): https://i.sstatic.net/Why29.png and sample object:

{
    "name": "SubtlePBR",
    "children": [
        {
            "name": "assets",
            "children": [
                {
                    "name": "minecraft",
                    "children": [
                        {
                            "name": "textures",
                            "children": [
                                {
                                    "name": "block",
                                    "children": [
                                        {
                                            "name": "acacia_leaves",
                                            "children": [],
                                            "isMat": true
                                        },
                                        {
                                            "name": "acacia_log",
                                            "children": [],
                                            "isMat": true
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

Answer №1

After spending a considerable amount of time working on this problem, I finally cracked it:

  function filterTree(tree: FileTreeProps): FileTreeProps | undefined {
    const filter =
      tree.children &&
      tree.children.length > 0 &&
      (tree.children
        .map((child) => filterTree(child))
        .filter((child) => child !== undefined) as FileTreeProps[]);

    const compareQueryAndName =
      tree.name.toLowerCase().includes(query.toLowerCase()) ||
      query.toLowerCase().includes(tree.name.toLowerCase());
    if (tree.isMat && compareQueryAndName) {
      return tree;
    }

    if (!tree.isMat && tree.name !== query && filter && filter.length > 0) {
      return { name: tree.name, children: filter };
    }

    return undefined;
  }

Answer №2

Although the original poster already provided a solution to his question, I would like to contribute my own take on it:

function filterDiagnosisTree(
    parent: Diagnosis, 
    filter: Diagnosis[]
  ): Diagnosis | undefined {
    const filtered: Diagnosis[] = parent.children && parent.children.length > 0
      ? parent.children.map((child) => filterDiagnosisTree(child, filter))
        .filter((child) => child !== undefined) as Diagnosis[]
      : [];
  
    if (filter.find((filterChild: Diagnosis) => filterChild.id === parent.id)) 
      return parent;
  
    if (filtered.length > 0) 
      return { ...parent, children: filtered };
  
    return undefined;
  }

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

A more efficient method for importing numerous 'export' statements using ES6 or TypeScript

Currently, I am utilizing D3.js V4 with the module and my goal is to import multiple modules into a singular namespace. The code snippet provided below showcases my current approach, but I am curious if there is a more efficient method available. const d3 ...

Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively. Any assistance on how to hide divs properly will be greatl ...

The module '*/node_modules/ngx-echarts/ngx-echarts' does not have the exported member 'Ngx Echarts Service' available for use

Initially, my Angular 6 project was functioning perfectly with all the packages in working order. However, upon attempting to upgrade it to Angular 8, I encountered the following error message when running ng serve: The module '"*/node_modules/ngx ...

Adding dropdowns to divs in Angular applications

Currently, I am attempting to integrate a dropdown feature into a div element. The HTML code for the dropdown is generated dynamically within the code. When clicking on the dropdown button, it appears functional but unfortunately, the dropdown itself does ...

What is a more effective approach for managing form data with React's useState hook?

Seeking a more efficient solution to eliminate redundancy in my code. Currently, I am utilizing useState() for managing user data, which results in repetition due to numerous fields. Below is a snippet of my current code: const [lname, setLast] = useState& ...

Queries are failing to pass the test requests

I'm facing a challenge in passing the test for a freeCodeCamp project that involves adding from, to, and limit parameters to a GET /api/users/:_id/logs request to fetch part of a user's log. From and to represent dates in yyyy-mm-dd format, while ...

How can I clear the cache for GetStaticPaths in NextJs and remove a dynamic route?

This question may seem basic, but I can't seem to find the answer anywhere online. Currently, I am diving into NextJs (using TypeScript) and I have successfully set up a site with dynamic routes, SSR, and incremental regeneration deployed on Vercel. ...

What is the process of generating a map from a class to retrieve its attributes as values?

I am looking to establish a more robust type-safe connection between an Angular template and a FormGroup. I have an idea in mind but I'm unsure how to properly implement it in TypeScript. My goal is to utilize an object to define the keys of the cont ...

Measuring Feedback: Utilizing Angular 4 to calculate review ratings

I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects ...

Creating custom declaration files in Typescript

I'm currently in the process of converting my project to Typescript. I've installed the latest @types and am in the midst of creating a custom.d.ts file. Here is what the file looks like so far: /// <reference path="../../../node_modules/@typ ...

Issues with Angular 9 application compatibility with IE11

Our Angular 9 project runs smoothly on Google Chrome and Firefox, but nothing appears on IE11. Despite trying various solutions found online and following related blogs, the issue remains unresolved. Here is a snippet from my tsconfig.json: { // Com ...

Both undefined and null are sometimes allowed as values in conditional types, even when they should not be

Do you think this code should trigger a compiler error? type Test<T extends number | string> = { v: T extends number ? true : false } const test: Test<1> = { v: undefined } Is there something I am overlooking? Appreciate your help! ...

Issue with accessing storage in Ionic Storage (Angular)

Currently, I am attempting to utilize Ionic storage for the purpose of saving and loading an authentication token that is necessary for accessing the backend API in my application. However, I am encountering difficulties retrieving the value from storage. ...

Leverage the TypeScript-generated controller within an Angular directive

I currently have an Angular controller that was generated using TypeScript: class FileManagerController { ... constructor($scope) { $scope.vm = this; ... } ...functions... } Can you guide me on how to integrate this controller i ...

The display of the key property is missing on the rendered page in a React TypeScript project

While working with Typescript React, I encountered an error message: react-jsx-dev-runtime.development.js:87 Warning: Each child in a list should have a unique "key" prop. Even though I included a key in the li tag like this: const MyMenuItem: ...

Changing array in TypeScript/Angular

I'm attempting to transform an array of strings into an array of key-value pairs, like this: ["x", "y"] transforms into [{"Value":"x"}, {"Value":"y"}] Any tips or guidance would be highly appreciated. Thank you! ...

Utilizing Angular's FormGroup within a FormArray for a novel control structure

In my Angular application, I am working with a reactive form that contains a formArray of formGroups named sections: sectionForm = new FormGroup({ title: new FormControl<string>('New Section', {nonNullable: true, validators: ...

Error in main.ts due to issues with importing components using an index.ts file

I am facing a common exception: Unexpected directive value 'undefined' on the View of component 'AppComponent' Many solutions I found online did not address my specific issue related to circular dependencies or missing export statem ...

What is the process for inputting a predefined function into an interface?

In my project, I have a Locale interface that defines the properties of a locale for my component: interface Locale { src: string; alt: string; language: string; i18nFormat: string; } During debugging, I am using the built-in .toSource() function ...

Enhance the performance of page loading and implement a consistent spinner feature to ensure smooth transitions for users in Next.js version 13

I am currently working on a project using Next.js 13, and I am encountering issues with slow loading times and an unstable spinner when navigating between pages. Specifically, when transitioning from the home page to the /example page, the experience is n ...