Home > OS >  Code refactor with functions in JavaScript
Code refactor with functions in JavaScript

Time:03-04

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])

CodePudding user response:

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]));

  • Related