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

79
Visualizações
order and organize array of objects

I have this array of objects and I want to organize the objects based on their units like this:

const array = [
  { unit: 5, id: 'five'},
  { unit: 200, id: 'some22'},
  { unit: 100, id: 'recall'},
  { unit: 5, id: 'some'},
];

// Result :

[

  [ { unit: 5, id: 'five'}, { unit: 5, id: 'some'}, ],
  [ { unit: 6, id: 'some22'} ],
  [ { unit: 55, id: 'recall'} ],

]

Note: we can simply use filter method to get the array but in my case we don't know the units and we just want to order and organize them

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A different approach using the build in array method reduce, just to create a one-liner. Details to the under appreciated reduce function Array.prototype.reduce

// Initial Data
const array = [
  { unit: 5, id: 'five'},
  { unit: 200, id: 'some22'},
  { unit: 100, id: 'recall'},
  { unit: 5, id: 'some'},
];

let result = array.reduce (function(last, next){ 
  // find index of a List with matching unit
  let index = last.findIndex((itemList) => itemList.some( item => item.unit == next.unit)); 
  if(index == -1){ // if no match was found
    index = last.push([]) - 1; // add an empty Array and set the index
  }
  last[index].push(next);  // add the Entry to the selected List
  return last;
}, [])

console.info(result);

btw.: I'm asuming the posted result data is incorrect, since the "units" for some22 and recall don't match with the initial data. If this assumption is wrong please clarify

Extra: just for kicks and giggles the whole thing as a real one-liner:
( Don't try this at home ;-) )

const array = [
  { unit: 5, id: 'five'},
  { unit: 200, id: 'some22'},
  { unit: 100, id: 'recall'},
  { unit: 5, id: 'some'},
];

console.info( array.reduce((p, c) => ((p.find( l => l.some(i => i.unit == c.unit)) || p[p.push([]) - 1]).push(c), p), []));

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use a Map:

const array = [
    { unit: 5, id: 'five'},
    { unit: 200, id: 'some22'},
    { unit: 100, id: 'recall'},
    { unit: 5, id: 'some'},
];

const unitGroups = new Map();
for (const obj of array) {
    if (!unitGroups.has(obj.unit)) {
        unitGroups.set(obj.unit, []);
    }
    unitGroups.get(obj.unit).push(obj);
}

const result = Array.from(unitGroups.values());
console.log(result);

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