Búsqueda de sitios web

javascript - ¿Cuál es el equivalente en Typescript de C# LINQ GroupBy?


Estoy usando Angular con Typescript. Tengo un arreglo de objetos con múltiples propiedades. Los he agrupado en el código del servidor y establecido la propiedad duplicada. Cuando el usuario actualiza la lista, tengo que recorrer la lista y encontrar duplicados en el lado del cliente. ¿Existe algún equivalente de C# LINQ GroupBy en Typescript?

Aquí está mi código C# LINQ:

listMP.Where(item => item.Type == "Other").GroupBy(i => new { i.Type, i.Name, i.Address1, i.City }).Where(g => g.Count() > 1)
.SelectMany(g=>g.Select(gg =>gg.Id));

Respuesta #1

Hay una biblioteca de TypeScript para LINQ.

Se llama ts-generic-collections-linq.

Proporcionando colecciones fuertemente tipadas y consultables como:

  • Lista
  • Diccionario

Fácil de usar.

NPM

https://www.npmjs.com/package/ts-generic-collections-linq

Ejemplo de consulta linq:

//query to get owners by the sex/gender of their pets
let ownersByPetSex = owners.join(pets, owner => owner.id, pet => pet.ownerId, (x, y) => new OwnerPet(x,y))
                           .groupBy(x => [x.pet.sex])
                           .select(x =>  new OwnersByPetSex(x.groups[0], x.list.select(x => x.owner)));

Respuesta #2

Una pregunta tan antigua, sin embargo, en mi opinión, aún no se ha dado una respuesta sencilla en TypeScript.

Así es como se hace un groupBy en TypeScript con reduce:

const grouped  = myArray
        .reduce(
            (g: { [id: string]: MyObject[] }, o: MyObject) => {
                g[o.FK] = g[p.FK] || []; //check if key allready exists, else init a new array
                g[o.FK].push(o);   //add item to array
                return g;     // be sure to return, or g will be undefined in next loop
            }, 
            {}    //a second parameter to the reduce function, important to init the returned object
        );

Artículos relacionados