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

160
Visualizações
compare 2 arrays based on id as the key and create 2 more arrays out of the comparison

I have 2 arrays (array1 and array2). I want to compare array1 and array2 by using 'id' as the key and want to create 2 resultant arrays out of array2.

  1. First array should contain all the objects which is present in array2 but not in array1.
  2. Second array should contain all the objects which is present in array1 and array2 both, common ones.
const array1 = [{ id: 176770 }, { id: 176771 }, { id: 176820 }];

const array2 = [
    { id: 176770, classfication: "comeone", type: "typeee" },
    { id: 176771, classfication: "comeone1", type: "typeee1" },
    { id: 176820, classfication: "comeone2", type: "typeee2" },
    { id: 176670, classfication: "comeone", type: "typeee" },
    { id: 176761, classfication: "comeone1", type: "typeee1" },
    { id: 176845, classfication: "comeone2", type: "typeee2" },
];

Please help me out to create these 2 arrays.

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

0

You can loop over the second array and find for an element with same id in first array. If there is no element present in first array, then your first condition is satisfied (Store it in result1). If the element exists in first array, your second condition is satisfied (Store it in result2)

const array1 = [{ "id": 176770 }, { "id": 176771 }, { "id": 176820 }]

const array2 = [{ "id": 176770, "classfication": "comeone", "type": "typeee" }, { "id": 176771, "classfication": "comeone1", "type": "typeee1" }, { "id": 176820, "classfication": "comeone2", "type": "typeee2" }, { "id": 176670, "classfication": "comeone", "type": "typeee" }, { "id": 176761, "classfication": "comeone1", "type": "typeee1" }, { "id": 176845, "classfication": "comeone2", "type": "typeee2" }]

let result1 = []
let result2 = [];

for (let element of array2) {
  let existingInFirst = array1.find(ele => ele.id == element.id);
  if (!existingInFirst) {
    result1.push(element)
  }
  else{
    result2.push(element)
  }
}

console.log(result1)
console.log(result2)

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