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

206
Visualizações
Code refactor with functions in JavaScript

I'm trying to refactor JS code into functions. I'm comparing two arrays and return a new array with any items only found in one of the two given arrays, but not both.

The code below works, but obviously it's not DRY principal.

function diffArray(arr1, arr2) {
  let newArr = []
  for(let el2 of arr2) {
    if(!arr1.includes(el2)) {
      newArr.push(el2)
    }
  }
  for(let el1 of arr1) {
    if(!arr2.includes(el1)) {
      newArr.push(el1)
    }
  }
  return newArr;
}

I want to turn the loop block into a function and below is what i came up with. However, it returns an empty array. What's the issue here?

let newArr = []

function singleEl(arrA, arrB) {
  for(let el of arrA) {
    if(!arrB.includes(el)) {
      newArr.push(el)
    }
  return newArr
}}

function diffArray(arr1, arr2) {
  singleEl(arr2, arr1)
  singleEl(arr1, arr2)
  return newArr;
}

  diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4])
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your problem is return newArr inside the loop.

function singleEl(arrA, arrB) {
  let newArr = [];
  for (let el of arrA) {
    if (!arrB.includes(el))
      newArr.push(el);
  }
  return newArr;
}

function diffArray(arr1, arr2) {
  let result = [];
  result = [...singleEl(arr1, arr2), ...singleEl(arr2, arr1)];

  return result;
}

console.log(diffArray([1, 2], [1, 5, 6]));
console.log(diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]));

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