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

200
Visualizações
How to find symmetrical difference using JavaScript?

I've been working on an algorithm that will find the symmetric difference of two arrays (i.e. only items that are in 1 of the 2 arrays, but not both). I've come up with the following so far:

function diffArray(arr1, arr2) {
  let newArr1 = arr1.slice();
  let newArr2 = arr2.slice();
  if (newArr1.length > newArr2.length) {
    return newArr1.filter((item) => !(item in newArr2));
  } else {
    return newArr2.filter((item) => !(item in newArr1));
  }
};

const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(result);

But when testing with diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) the output is [4, 5] instead of just [4]. The issue seems to happen with whatever the last value of either array is, but I can't seem to figure out what about my code is causing the issue. Thanks in advance for any help.

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

0

The in operator checks if the value on the left matches a property name on the right.

In you want to check if one of the property values is in an array, use the includes method.

function diffArray(arr1, arr2) {
  let newArr1 = arr1.slice();
  let newArr2 = arr2.slice();
  if (newArr1.length > newArr2.length) {
    return newArr1.filter((item) => !newArr2.includes(item));
  } else {
    return newArr2.filter((item) => !newArr1.includes(item));
  }
};

const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Updating the answer for another condition

const result = diffArray([1, 2, 3, 4], [1, 2, 3, 5]);

function diffArray(arr1, arr2){
  const diff1 = arr1.filter(item => !arr2.includes(item)); // if item not available, the value will be filtered
  const diff2 = arr2.filter(item => !arr1.includes(item));// if item not available, the value will be filtered
  return diff1.concat(diff2);
}
// const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
const result = diffArray([1, 2, 3, 4], [1, 2, 3, 5]); // This condition will fail on the above code
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