Discovering nested trees within a tree structure in typescript

Imagine having a tree structure in JavaScript like this:

a1 
--b
----c1
a2
--b2
--b3
----c2

If you needed to find c2, the path would be a2->b3->c2

Now, consider the following JSON object representing a family tree:

treeFamily = {
            name : "Parent",
            children: [{
                name : "Child1",
                children: [{
                    name : "Grandchild1",
                    children: []
                },{
                    name : "Grandchild2",
                    children: []
                },{
                    name : "Grandchild3",
                    children: []
                }]
            }, {
                name: "Child2",
                children: []
            }]
        };

Answer №1

To determine if the nested children contain the desired key/value pair, you can examine them and then pass the name to the outer function.

function searchPath(array, target) {
    var path;
    array.some(({ name, children }) => {
        var temp;
        if (name === target) {
            path = [name];
            return true;
        }
        if (temp = searchPath(children, target)) {
            path = [name, ...temp];
            return true;
        }
    });
    return path;
}

var familyTree = { name: "Ancestor", children: [{ name: "Descendant1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Descendant2", children: [] }] };

console.log(searchPath([familyTree], 'Grandchild2'));
console.log(searchPath([familyTree], 'bar'));

Answer №2

To locate specific nodes in a tree structure, you can utilize the for...of loop to search through the children recursively. When the target node is found, its name is returned and concatenated with the names of its ancestors. If the node is not found, the function will either return undefined or an empty array.

const findNodePath = (targetName, { name, children }) => {
  if(name === targetName) return [name];
  
  for(const child of children) {
    const result = findNodePath(targetName, child);
    if(result) return [name, ...result];
  }
  
  // Return undefined implicitly when child is not found, or explicitly return [] to get an empty array
};

const familyTree = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] };

console.log(findNodePath('Child2', familyTree));
console.log(findNodePath('Grandchild3', familyTree));
console.log(findNodePath('Grandchild400', familyTree));

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

VueJS is unable to identify the variable enclosed within the curly braces

I recently started learning VueJS and I've hit a roadblock. My goal is to display a variable, but for some reason, instead of seeing the product name, all I get is {{product}} Here's the HTML code I'm using: <!DOCTYPE html> <html l ...

Angular encounters an issue where it is unable to access a property within a directive

Currently, I am utilizing the angular-media-player module from https://github.com/mrgamer/angular-media-player. Here is how my HTML code looks: <audio media-player="audioControl" data-playlist="list" a="{{audioControl.ended}}"> I am able to access ...

Exploring sections of a non-contiguous array in Numpy by considering them as a single contiguous unit with a

My goal was to create an array of trigrams (three-letter combinations) from a very long character array: # loading data from a source file a = np.random.randint(0, 256, 2**28, 'B').view('c') Instead of inefficiently making a copy, whic ...

Sending information from a Vuex module to a component following an axios request

I'm currently working on developing a Vue.js based application. Here's the scenario I'm facing: I have a component with a popup where users can create an 'expense' entry. Upon clicking the 'save' button, a function in the ...

How does the use of let versus const differ when iterating through a collection?

Utilizing Node.js (ES6) to iterate through each item in a collection like the one provided below: var statuses = [{ statusId: 1, description: 'New' }, { statusId: 2, description: 'Pending' }, { ...

Tips for modifying CSS when a user scrolls beyond a specific div

Currently, I am working on implementing a scroll function that dynamically moves elements based on the user's scrolling behavior. The code I have written works to some extent and successfully moves the elements. However, my goal is to create a list o ...

Creating a direct connection between a parent node and all of its children in OrgChartjs

Can I connect all children directly to one parent in Balkan OrgChart.js? This is my starting point based on the documentation of OrgChart.js. window.onload = function () { OrgChart.templates.family_template = Object.assign({}, OrgChart.templates.ana); ...

Is there a way to conceal a slice of a pie chart in HighCharts without excluding it from the legend display?

I've been searching everywhere for a solution to this issue, but I just can't seem to pinpoint where I'm going wrong. My goal is to initiate a pie chart using HighCharts with specific slices hidden as if they were "clicked" off in the legen ...

Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application. I have a parent component that loads some data: In admin-area.component.ts: ngOnInit(): void { forkJo ...

Leveraging the Mutation hook for updating information on a Graphql server

Recently, I encountered an issue while utilizing the useMutation hook in React Native to update data on my server within a project I'm working on. The file where I'm implementing this hook is attached for reference. I've also included a scr ...

Issues with displaying output in C++ arrays

Being relatively new to C++, I acknowledge this question may appear quite basic (or even dumb!). My goal is to return an array of (int i, int j) representing a position or coordinates. Below is the code I've been working on: int* PositionCalculator(i ...

Using React, TypeScript, and Next.js to transform all elements in a static array to their last occurrence

I'm having trouble updating my array. Every time I click the button for the second time, only two or more records are added, similar to the last one I added. Does anyone know how to fix this issue? In the images below, you can see the results of the ...

Keyboard input that allows for diagonal movement in games at the same time

Currently, I am developing a 2D game using Node where the character must move diagonally. This game is top-down and text-based, existing solely within a Node environment without traditional browser features like keydown/keyup events. To handle user input, ...

Top tip for receiving a JSON response object using AngularJS

I am currently working with an API that returns a json array object. In my Controller, I have been able to retrieve the json data successfully using the following code: angular.module('lyricsApp', []) .controller('LyricsController', [& ...

Unit Testing Angular: Mastering Unit Testing for the .map() Function

I am in need of testing a service method, but I am unsure about how to achieve complete coverage for the code that gets executed as a result of calling another injected service method. The Service Method to be tested: @Injectable() export class BomRevisi ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

Converting a List of Object arrays into a String array in Java

I tried various methods to convert a List< Object > to a String[], but none of them seem to work for a List< Object[] >. I keep encountering the following error: java.lang.RuntimeException: java.lang.ClassCastException: [Ljava.lang.String; can ...

Is your Node.js HTTP Request failing to function properly?

I am currently working on creating an HTTP Request function where all requests are directed to the same domain but with different file names. Unfortunately, I am encountering a problem where nothing is being displayed in the console and no data is being r ...

Loading the JS file after waiting on Lib (IronRouter) causes the HTML not to load properly

Currently, I am utilizing wait-on-lib along with IRLibLoader.load() in conjunction with Iron-Router, following the instructions provided in the tutorial found at: . My objective is to load external javascript code. Below is a snippet of my routing code: R ...