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

205
Visualizações
How to merge and group arrays of objects by ids?

I need to unite two arrays with objects with equal id.

const arr1 = [{id: 1, name: 'John'}, {id: 10, name: 'Janny'}, {id: 22, name: 'Mark'}];
const arr2 = [{id: 1, name: 'John', phone: '111'}, {id: 15, name: 'Nick'}, {id: 22, name: 'Mark'}];

The result should be

[
  {id: 1, name: 'John', phone: '111'}, 
  {id: 15, name: 'Nick'},
  {id: 22, name: 'Mark'},
  {id: 10, name: 'Janny'}
]

I tried to use lodash _.isEqual(arr1, arr2) but it's not working, because {id: 1, name: 'John', phone: '111'} is not equal to {id: 1, name: 'John'}.

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

0

You can combine the elements in the arrays, group them by id using a map or an object, and get the values:

const arr1 = [
  { id: 1, name: 'John' },
  { id: 10, name: 'Janny' },
  { id: 22, name: 'Mark' },
];
const arr2 = [
  { id: 1, name: 'John', phone: '111' },
  { id: 15, name: 'Nick' },
  { id: 22, name: 'Mark' },
];

const result = [
  ...[...arr1, ...arr2]
    .reduce(
      (acc, curr) => acc.set(curr.id, { ...acc.get(curr.id), ...curr }),
      new Map()
    )
    .values(),
];
console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

here is a very stupid and long way to do it:

const arr1 = [{id: 1, name: 'John'}, {id: 10, name: 'Janny'}, {id: 22, name: 'Mark'}];
const arr2 = [{id: 1, name: 'John', phone: '111'}, {id: 15, name: 'Nick'}, {id: 22, name: 'Mark'}];
let newArr = [];
firstLoop: for(let i=0; i < arr1.length; i++){
    for(let j =0; j < arr2.length; j++){
        if(arr1[i].id == arr2[j].id){
            newArr.push({...arr1[i], ...arr2[j]})
            continue firstLoop;
        }
    }
    newArr.push(arr1[i])
}
firstLoop: for(let i=0; i < arr1.length; i++){
    for(let j =0; j < arr2.length; j++){
        if(arr2[i].id == arr1[j].id){
            // newArr.push({...arr1[i], ...arr2[j]})
            continue firstLoop;
        }
    }
    newArr.push(arr2[i])
}
console.log(newArr);

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