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

100
Visualizações
Modify objects in resutl array when combining two arrays into one

I have two arrays of objects (Array1 and Array2) that I must combine in one array (result).

If an value is present in both arrays, it should be only once in the final array.

If a value is not present in any of the arrays, it needs to be added with the boolean set to true.

Here's the situation:

const Array1 = [
{value: "id1", name: "Element1", boolean: false}, 
{value: "id2", name: "Element2", boolean: false}, 
{value: "id3", name: "Element3", boolean: false}
]

const Array2 = [
{value: "id1", name: "Element1", boolean: false}, 
{value: "id2", name: "Element2", boolean: false}, 
{value: "id4", name: "Element4", boolean: false}
]

Expected output:

const result = [
{value: "id1", name: "Element1", boolean: false}, 
{value: "id2", name: "Element2", boolean: false}, 
{value: "id3", name: "Element3", boolean: true}, 
{value: "id4", name: "Element4", boolean: true}
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can easily achieve the result using Map

const Array1 = [
  { value: "id1", name: "Element1", boolean: false },
  { value: "id2", name: "Element2", boolean: false },
  { value: "id3", name: "Element3", boolean: false },
];

const Array2 = [
  { value: "id1", name: "Element1", boolean: false },
  { value: "id2", name: "Element2", boolean: false },
  { value: "id4", name: "Element4", boolean: false },
];

const map = new Map(Array1.map((o) => [o.value, [o]]));
Array2.forEach((o) =>
  map.has(o.value) ? map.get(o.value).push(o) : map.set(o.value, [o])
);
const result = [...map.values()].map((arr) =>
  arr.length > 1 ? arr[0] : { ...arr[0], boolean: true }
);

console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

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