0

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])
tommy-ling
  • 49
  • 9

1 Answers1

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]));
Miheo
  • 517
  • 9
  • 19
  • Thank you i didn't notice that. However, with this piece of code, whenever i test a new array, the result from the previous test stays in the array and it keeps adding on. I think it's because of the let newArr = [] being outside the functions. If I put it in the function it becomes undefined in the other function. Is there any solution to that? Or this refactoring is just not optimal for this purpose? – tommy-ling Mar 02 '22 at 11:56
  • Hi, I have updated the code above. For reusing purpose, you should return result as an array in each function. – Miheo Mar 03 '22 at 03:22