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

134
Visualizações
How to group array element to a new group array?

I have an array of lines:

   this.lines = [
    0: {indexLine: 0, group: 16, columns: [,…]}
    1: {indexLine: 1, group: 16,…}
    2: {indexLine: 2, group: 16,…}
    3: {indexLine: 3, group: 9,…}
    ]

I want to group lines by group to be able render it in different tables.

I have tried this:

 let arr: any = {};
        this.lines.forEach((line) => {
          if (!arr[line.group]) {
            arr[line.group] = [];
          }

          arr[line.group].push(line);
        });
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Set to get unique group values from array of object. new Set(lines.map(x => x.group) will give you array of unique values of group.

Convert that set to array with Array.from().

Now you can use map to iterate through unique group values and Array.filter would give you all matching elements.


let lines = [
    {indexLine: 0, group: 16},
    {indexLine: 1, group: 16},
    {indexLine: 2, group: 16},
    {indexLine: 3, group: 9},
];

const groupedLines = Array.from(new Set(lines.map(x=>x.group))).map(y => lines.filter(z => z.group === y));

console.log(groupedLines);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use the reduce method to get what you want:

const result = this.lines.reduce((acc, item) => {
  if (!acc[item.group]) {
    acc[item.group] = [];
  }
  acc[item.group].push(item);
  return acc;
}, {});

If you want to get all the groups as multiple arrays instead of an object, you can use Object.values to do just that:

const groups = Object.values(result);
about 4 years ago · Juan Pablo Isaza Relatório

0

you can use lodash.groupBy

yarn add lodash.groupby ( or npm install lodash.groupby --save )

import groupBy from 'lodash.groupby'; // 12.6k (gzipped 4.8k)

// ...

console.log(groupBy(this.lines, ({group}) => group)));

( self-explanatory code there, 0 WTFs per minute )

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