Search code examples
javascriptarraysdifferencesymmetric-difference

How to find symmetrical difference using JavaScript?


I've been working on an algorithm that will find the symmetric difference of two arrays (i.e. only items that are in 1 of the 2 arrays, but not both). I've come up with the following so far:

function diffArray(arr1, arr2) {
  let newArr1 = arr1.slice();
  let newArr2 = arr2.slice();
  if (newArr1.length > newArr2.length) {
    return newArr1.filter((item) => !(item in newArr2));
  } else {
    return newArr2.filter((item) => !(item in newArr1));
  }
};

const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(result);

But when testing with diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) the output is [4, 5] instead of just [4]. The issue seems to happen with whatever the last value of either array is, but I can't seem to figure out what about my code is causing the issue. Thanks in advance for any help.


Solution

  • The in operator checks if the value on the left matches a property name on the right.

    In you want to check if one of the property values is in an array, use the includes method.

    function diffArray(arr1, arr2) {
      let newArr1 = arr1.slice();
      let newArr2 = arr2.slice();
      if (newArr1.length > newArr2.length) {
        return newArr1.filter((item) => !newArr2.includes(item));
      } else {
        return newArr2.filter((item) => !newArr1.includes(item));
      }
    };
    
    const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
    console.log(result);