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

180
Vistas
How to group array items as a specific typescript type?

lets say I have this array:

  const dataUse = [
    { group: 'z', name: 'hello' },
    { group: 'z', name: 'hello2' },
    { group: 'z', name: 'hello3' },
    { group: 'x', name: 'hello1' },
    { group: 'x', name: 'hello2' }
  ];

I want to group it on group and I do so by:

group func:

  const groupBy = <T, K extends keyof any>(arr: T[], key: (i: T) => K) =>
    arr.reduce((groups, item) => {
      (groups[key(item)] ||= []).push(item);
      return groups;
    }, {} as Record<K, T[]>);

calling:

  const grouped = groupBy(dataUse, (i) => i.group);

result:

{
x: Array
z: Array
}

Problem:

I need to be able to access the properties and in my case x and z are dynamic and will never have the same name. So I thought that I need to group my data as a specific container type:

type GroupContainer = {
  group: string;
  items: Array<MyListObj>;
};

Desiered output would be:

[
{Group: 'x', items:Array}
{Group: 'z', items:Array}
]

The helper func does turns this into records and Im not sure how to turn it into GroupContainer

How do I accomplish this?

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Object.entries will give us an array with key-value pairs, so we can just map over them and use them for our object:

Object.entries(grouped).map(([group, items]) => ({ group, items }))

Playground

almost 4 years ago · Santiago Trujillo Denunciar
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