Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
Group by array of objects in TypeScript without sorting

I'm working on an array of object to group them according to the key(number), but it always ends up sorting the array. So is there any solution using Map() to perform group by or any TypeScript solution for it.

const reGroup = (list, key) => {
    const newGroup = {};
    list.forEach(item => {
        const newItem = Object.assign({}, item);
        newGroup[item[key]] = newGroup[item[key]] || [];
        newGroup[item[key]].push(newItem);
    });
    return newGroup;
};
const pets = [
    {type:"Dog", age: "5", name:"Spot", },
    {type:"Cat", age: "3", name:"Tiger",},
    {type:"Dog", age: "2", name:"Rover",  }, 
    {type:"Cat", age: "3", name:"Leo", }
];

const grouped = reGroup(pets, "age");
console.log(grouped);

Output:

       {
     "2": [ { "type": "Dog", "age": "2", "name": "Rover" } ],
     "3": [ { "type": "Cat", "age": "3", "name": "Tiger" },
           { "type": "Cat", "age": "3", "name": "Leo" } ],
     "5": [ { "type": "Dog", "age": "5", "name": "Spot" } ]
     }

Expected:

       {        
         "5": [ { "type": "Dog", "age": "5", "name": "Spot" } ],
         "3": [ { "type": "Cat", "age": "3", "name": "Tiger" },
               { "type": "Cat", "age": "3", "name": "Leo" } ],
         "2": [ { "type": "Dog", "age": "2", "name": "Rover" } ],
         }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use an array instead of an object. Order of keys in objects cannot be guaranteed.

Try:

  const reGroup = (list, key) => {
    const groups = [];
    list.forEach(item => {
        let groupIndex = groups.findIndex((gi) => gi.key === item[key]);
        if (groupIndex === -1) {
          // when the group containing object does not exist in the array, 
          // create it
          groups.push({key: item[key], items: []});
          groupIndex = groups.length - 1;
        }
        const newItem = Object.assign({}, item);
        groups[groupIndex].items.push(newItem);
    });
    return groups;
  };
  const pets = [
      {type:"Dog", age: "5", name:"Spot", },
      {type:"Cat", age: "3", name:"Tiger",},
      {type:"Dog", age: "2", name:"Rover",  }, 
      {type:"Cat", age: "3", name:"Leo", }
  ];

  const grouped = reGroup(pets, "age");
  console.log(JSON.stringify(grouped, null, 2));

which logs:

[
  {
    "key": "5",
    "items": [
      {
        "type": "Dog",
        "age": "5",
        "name": "Spot"
      }
    ]
  },
  {
    "key": "3",
    "items": [
      {
        "type": "Cat",
        "age": "3",
        "name": "Tiger"
      },
      {
        "type": "Cat",
        "age": "3",
        "name": "Leo"
      }
    ]
  },
  {
    "key": "2",
    "items": [
      {
        "type": "Dog",
        "age": "2",
        "name": "Rover"
      }
    ]
  }
]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda