Array symmetric difference

JavaScript, Array, Math · Oct 22, 2020

Returns the symmetric difference between two arrays, without filtering out duplicate values.

  • Create a Set from each array to get the unique values of each one.
  • Use Array.prototype.filter() on each of them to only keep values not contained in the other.
const symmetricDifference = (a, b) => {
  const sA = new Set(a),
    sB = new Set(b);
  return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
};
symmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
symmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3]

More like this

  • JavaScript Math

    A snippet collection of math helpers and algorithms implemented in JavaScript.

    Collection · 95 snippets

  • Array unique symmetric difference

    Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.

    JavaScript, Array · Oct 22, 2020

  • Array difference

    Calculates the difference between two arrays, without filtering duplicate values.

    JavaScript, Array · Oct 19, 2020

  • Mapped array symmetric difference

    Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.

    JavaScript, Array · Oct 22, 2020