Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. For example diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) should return [4]

Solution 1

function diffArray(arr1, arr2) {
  var newArr = [];
  arr1.forEach(elem => {
    if (arr2.indexOf(elem) === -1) {
      newArr.push(elem);
    }
  });

  arr2.forEach(elem => {
    if (arr1.indexOf(elem) === -1) {
      newArr.push(elem);
    }
  });
  return newArr;
}

 

Solution 2

function diffArray(arr1, arr2) {
  let newArray = arr1
    .concat(arr2);
  newArray = newArray.filter(elem => newArray.indexOf(elem) === newArray.lastIndexOf(elem));
  return newArray;
}

 

Solution 3

function diffArray(arr1, arr2) {
  var newArr = [...diff(arr1, arr2), ...diff(arr2, arr1)];
  function diff(a, b) {
    return a.filter(elem => b.indexOf(elem) === -1);
  }
  return newArr;
}

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