Typescript Algorithm - Node Tree: A unique approach combining algorithmic concepts and

I am dealing with a json data in raw format that is unsorted. Here is a snippet of the data:

[
  {
    "level": 1,
    "id": 34,
    "name": "example-name",
    "father_id": 10
  },
  ...
]

My goal is to organize this data in a specific way as shown below:

...

In order to achieve this transformation efficiently, I have implemented the following solution in typescript:

    const families: { parent: Treeview; children: Treeview[] }[] = []

    arrayTreeViews.forEach(node => {
      ...
    })

I am seeking advice on whether this is the most efficient way to accomplish this task in typescript.

Thank you for any help or suggestions!

EDIT :

[Message deleted because it was the wrong solution]

EDIT 2 : Solution found : so same question as earlier ? Is it the best way / most efficient way to do it ? Thanks for your help / advice

    const rootLevel: { parent: Treeview; children: Treeview[] }[] = []
    const subLevel: Treeview[] = []
    const lowerLevel: Treeview[] = []

    arrayTreeViews.forEach(node => {
      ...
    })

    subLevel.forEach(node => {
      ...
    res.json(rootLevel)

Answer №1

Edit: Due to the change in the question, a new answer had to be crafted

const findChildren = (tree: Treeview[], node: Treeview) =>
  tree.filter(
    (treeNode) =>
      treeNode.level === node.level - 1 && treeNode.father_id === node.id
  );

const findGrandchildren = (tree: Treeview[], node: Treeview) =>
  findChildren(tree, node).flatMap((child) => findChildren(tree, child));

const families = arrayTreeViews
  .filter((view) => view.level === 5)
  .map((view) => ({
    parent: view,
    children: findGrandchildren(arrayTreeViews, view),
  }));

Original Answer:

In this scenario, I would opt for a recursive approach:

const getRelation = (
  tree: Treeview[],
  lowerLevelBound: number,
  level: number,
  fatherId?: number
) => {
  // Locate nodes with the specified level
  const currentLevelNodes = tree.filter(
    (node) =>
      node.level === level &&
      // If fatherId is not null, filter nodes with the desired father_id
      (fatherId == null ? true : node.father_id === fatherId)
  );

  // Exit the algorithm when reaching the lower level bound
  if (level === lowerLevelBound) return currentLevelNodes;

  return currentLevelNodes.map((node) => ({
    parent: node,
    children: getRelation(tree, lowerLevelBound, level - 1, node.id),
  }));
};

const lowerLevelBound = 3;
const upperLevelBound = 5;

const families = getRelation(arrayTreeViews, lowerLevelBound, upperLevelBound);

This method involves filtering nodes of level 5 and recursively establishing parent-child relationships.

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

Come back to Angular 2 on your return function

Having a problem with an asynchronous function. There is a service that retrieves data from a Firebase database. One of the functions returns a value: historialDeConsumi() { this.item = this.af.database.object('/users/' + this.uid + '/a ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Tips on modifying the selected type key name through Pick?

I currently have this structure: type Product = { name: string } and I am looking to extract the name property and use it in a different type declaration like so: type NewProduct = Pick<Product, 'name'> Now, I want to rename name as new ...

What is the best way to retrieve the name of a static method within a class?

In my code, I am logging multiple messages in a static method and I want to use the method name as context. However, I do not want to create a separate variable called `context` and assign the function/method name to it. I would like to be able to access ...

Discover the elements within an array that appear an odd number of times

I've encountered a particular issue that I'm trying to solve: 'Identify all elements in an array that appear an odd number of times'. My approach towards this problem includes: Utilizing a HashMap: Storing values from the array as ...

Is it necessary to explicitly specify VOID when rejecting an empty Promise?

By default, promise rejection returns type void. Promise.reject(reason?: any) => void Imagine a scenario where we have a getUser function that retrieves a User object to be passed to a login function. We use a Promise that resolves when the user is ...

IntelliJ does not provide alerts for return type inconsistencies in TypeScript

During the development of our web application using react+typescript+spring boot with IntelliJ, everything seemed to be going smoothly until I came across an unexpected issue. Take a look at this code snippet example: export class TreeRefreshOutcome { } e ...

Defining a JSON file interface in Angular to populate a dropdown box with dependencies

I've embarked on an exciting project to develop a cascading dropdown box filter, and it's proving to be quite challenging. I'm taking it step by step to ensure clarity. I have obtained a JSON file containing the data required to populate de ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue. ...

What data structure is used to store HTML elements in TypeScript?

Currently, I am dealing with a typescript variable that holds the outcome of a query on the DOM: let games = document.getElementsByTagname("game"); My uncertainty lies in identifying the appropriate type for the resulting array. Should I expect an array ...

Issue with Dates in Typescript array elements

When attempting to compare different Date elements in my code, I encountered an issue. I have two date elements representing date formats but am unable to compare them because I keep receiving the error message "core.js:6237 ERROR TypeError: newticketList. ...

When navigating using the next and back buttons, the active state in Angular is automatically removed

Looking for some assistance with my quiz app setup. Each question has True/False statements with corresponding buttons to select T or F. However, when I click the next/back button, the active class is not being removed from the previous selection. As a beg ...

There is a type error in the dynamic assignment in TypeScript. I have various data that need to be fetched from one another

const obj1 = { a: 1, b: "xx" }; const obj2 = { a: 2, b: "3", d: "hello" }; for (const key in obj1) { const _key = key as keyof typeof obj1; obj1[_key] = obj2[_key]; } x[_key] error Type 'string | number' is no ...

A step-by-step guide to showcasing dates in HTML with Angular

I have set up two datepickers in my HTML file using bootstrap and I am attempting to display a message that shows the period between the first selected date and the second selected date. The typescript class is as follows: export class Datepicker { ...

Get the @types definition installed from a forked repository

Background Information I recently made a workaround for a single type definition in my fork of DefinitelyTyped. This fix is located on a specific branch within my fork. It's important to note that this fix is temporary and should not be merged back ...

Guide on validating multiple preselected checkboxes using Angular 8 reactive forms

I have a problem with validating checkboxes in my Angular application. The checkboxes are generated dynamically from an array using ngFor loop, and I want to make sure that at least one checkbox is selected before the form can be submitted. The validatio ...

"Enhancing User Experience with Angular 2: Customizing Component Selection and Sty

I am currently working on an Angular application that fetches a configuration file in .json format. My goal is to dynamically choose components and apply inline styles to them. Below is an example of the structure of the configuration data obtained from a ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

The module named "domhandler" does not have an exported member called 'DomElement'. Perhaps you meant to use 'import DomElement from "domhandler"' instead?

I am currently working on a react-typescript project and encountered an error while trying to build it. It seems that I forgot to install dom utils and HTML parser libraries, and now I am facing the following issue when I attempt to run yarn build: ...