Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda