Retrieve the IDs of all children and grandchildren within a parent ID using Typescript

If I were to have an array of objects containing hierarchical data:

const data = [
  { groupId: 1, parentGroupId: null },
  { groupId: 2, parentGroupId: 1 },
  { groupId: 3, parentGroupId: 1 },
  { groupId: 4, parentGroupId: null },
  { groupId: 5, parentGroupId: 99 },
  { groupId: 6, parentGroupId: 2 },
  { groupId: 7, parentGroupId: 6 },
  { groupId: 8, parentGroupId: 4 }];

How can a recursive TypeScript function be implemented that takes a parentGroupId parameter and returns an array of groupId's that includes the parent groupId and all its descendants, grandchildren, great-grandchildren, and so on recursively.

For example, the function should output:

[1,2,3,6,7]

Currently, a function exists that returns the parent and its immediate children, but the recursive aspect to include grandchildren, great-grandchildren, etc. is missing.

 const data = [
          { groupId: 1, parentGroupId: null },
          { groupId: 2, parentGroupId: 1 },
          { groupId: 3, parentGroupId: 1 },
          { groupId: 4, parentGroupId: null },
          { groupId: 5, parentGroupId: 99 },
          { groupId: 6, parentGroupId: 2 },
          { groupId: 7, parentGroupId: 6 },
          { groupId: 8, parentGroupId: 4 }];
          
    function getChildIds(arr, parentGroupId) {
      return arr.reduce(function (ret, item) {
        if (item.parentGroupId == parentGroupId || item.groupId == parentGroupId) {
          ret = ret.concat(item.groupId);
        }
        return ret;
      }, []);
    }

    console.log(getChildIds(data, 1));

Answer №1

After exploring different options, I decided to use the following function:

function retrieveChildIds(array: any[], parentID: number) {
  return array.reduce(function (result: any[], item: any) {
    if (item.parentID == parentID) {
      result = result.concat(item.ID, retrieveChildIds(array, item.ID));
    }
    return result;
  }, []);
}

This function retrieves all IDs except for the initial parent ID, which is then added to the array later on.

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

having difficulty applying a border to the popup modal

Currently, I am utilizing a Popup modal component provided by the reactjs-popup library. export default () => ( <Popup trigger={<button className="button"> Guide </button>} modal nested > {(close: any) =&g ...

Exploring the potential of AssemblyScript in creating immersive WebXR

I have been exploring three.js and webXR for some time now, and I wanted to incorporate it into assembly script. While I know how to make webXR work in TypeScript, I encounter an error when trying to use it in assembly script with the import statement. Her ...

Exploring Typescript keyof in Storybook's User Interface customizations

Currently, I am working on developing components for integration with Storybook, but I am encountering an issue related to Typescript inferred types. While striving for code reusability, I prefer not to specify the options for a control within the story i ...

The function __WEBPACK_IMPORTED_MODULE_3_ionic_native__.a.open is returning an error

Is there a way to troubleshoot and resolve the following error: WEBPACK_IMPORTED_MODULE_3_ionic_native.a.open is not a function while utilizing the NishanthKabra/Ionic2_GoogleCalendar solution. I am interested in integrating Google Calendar into my Io ...

How can I implement a dynamic progress bar using Ionic 4?

I am currently working on developing a progress bar that increases by 1% every time the user clicks a button. This is what my HTML code looks like: <ion-button *ngFor="let progress of progress" (click)="add(progress)">Progress</ion-button> &l ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

Managing status in Angular applications

I am currently working on a project using Angular 7 and I have the following code snippet: public deleteId(pId){ return this.http.delete<any>(this.deleteUrl(pId), {observe: 'response'}) .pipe(catchError(this.handleError)); } I ...

Ensuring Type Safety in Typescript

I have a specific requirement where I need to validate the structure of a request body to ensure it conforms to a predefined type. Is there a way or a package that can help achieve this validation? type SampleRequestBody = { id: string; name: string; ...

How can I retrieve the row index in an Angular Mat-Table that has expandable content?

Having a mat-table with expandable content on a page, I am seeking a solution to record the row number of the table when clicked. While I successfully achieved this with a regular table in the HTML file using: <tr mat-row *matRowDef="let row; columns: ...

How to incorporate a popup modal in your project and where should you place the DialogService constructor

Currently, I am in the process of developing a CRUD ASP.NET Core application using Angular 2 and Typescript. Prior to incorporating a popup feature, this was my output: https://i.stack.imgur.com/vHvCC.png My current task involves placing the "Insert or e ...

Achieving seamless integration among react-templates, TypeScript, and webpack

I am attempting to integrate TypeScript, react-templates, and webpack for a seamless workflow. My starting point was the sample code provided at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html. The configuration in the webpack.config ...

Angular - Monitoring Changes in Variables

I've recently started working with Angular, primarily using VueJS. I'm curious about how to detect when a variable is updated. In my case, the variable is being updated through a DataService. I came across ngOnChanges(), but it seems that it only ...

If every single item in an array satisfies a specific condition

I am working with a structure that looks like this: { documentGroup: { Id: 000 Children: [ { Id: 000 Status: 1 }, { Id: 000 Status: 2 ...

Troubleshooting Angular 2 Typescript: Component not displaying as expected

I am currently in the process of learning Angular 2. Despite encountering numerous error messages, I have successfully set up the routes and can now display the desired component. My next challenge is to incorporate a navbar component into my homepage comp ...

Having trouble sending correct true/false values for selected radio buttons on an Angular5 table, often requiring users to click them twice to submit the appropriate values

My goal is to assign true or false values to selected radio buttons in each row and then form an object for submission. To distinguish between the radio button values in each row, I have used {{k}}+{{sizeobj.rbSelected}} as the value which is causing issue ...

Linking key value pairs through a TypeScript interface

coding interface StoreActions { setUserName: string actionOne: string[] actionTwo: { testValue: string } } interface CustomActions extends AnyAction { typeOfAction: keyof StoreActions // additionalData:??? } The attribute typ ...

sequelize-typescript's findAll method within a HasMany relationship returns an object rather than an array

Trying to establish a one-to-many relationship with sequelize-typescript, encountering an issue where the many relationship returns an object instead of an array when retrieving the data. There are two tables involved: Team and Players. In this setup, a ...

Having trouble accessing props on children in TypeScript while using React.Children.toArray?

When using React.Children.toArray in Typescript, the props object on children is not detected. In order to address this issue, I am currently using any[] instead of ReactChild[], as props are not recognized on a array item when using the latter. Can someon ...