Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda