Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Recursive function to create a list from another deep list

Another question about recursive function, I cant get my head arround them. I have a list with groups that can have any depth, an example:

{
    Id: 1,
    Name:"Root",
    Children: [
      {
        Id: 1,
        Name:"",
        Children: [    
          {
           Id: 1,
           Name:"",
           Children: [
               {
                Id: 1,
                Name:"",
                Children: []
               },
             ]
         },
        ]
      },
      {
        Id: 2,
        Name:"",
        Children: []
      },
      {
        Id: 3,
        Name:"",
        Children: []
      },
    ]
}

I show these groups in a dropdown that the user can select. What I need to do is when the user clicks on any group, I need to show all users that are a part of that group AND its subgroups.

The information about which users belong to the group and its subgroups is hold by the userlist. That list is flat and every user has an prop that contains an membership array.

I have re-written this method below several times, this is the closest I get, but this more than doubles the expected lenght because I get dublicates.

const getAllUsersInGroup = (group, usersFiltered) => {
    if (!group.Children.length) return usersFiltered.flat();

    return group.Children.flatMap((g) => {
        return getAllUsersInGroup(
            g,
            [...usersFiltered, users.filter((u) => u.Memberships.some((m) => m.GroupId === g.Id))]
        );
    });
};

Another test returns almost all but there is missing users on bigger groups with many subgroups.

const getAllUsersInGroup = (group, userss) => {
    if (!group.Children.length) return [...userss].flat();

    return group.Children.flatMap((g) => {
        return getAllUsersInGroup(g, 
            users.filter((u) => u.Memberships.some((m) => m.GroupId === g.Id)),
        );
    });
};

I must be stuck in some wrong thinking or just pure stupid.. Maybe I dont need to check the Children lenght and just go thro them all, but as I understand it you need some statment that stops the method.

A little help would be much appreciated!

Regards

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!