Array difference

JavaScript, Array · Oct 19, 2020

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

const difference = (a, b) => {
  const s = new Set(b);
  return a.filter(x => !s.has(x));
};
difference([1, 2, 3, 3], [1, 2, 4]); // [3, 3]

More like this

  • JavaScript Array Set Operations

    Learn how to apply mathematical set operations to JavaScript arrays.

    Collection · 12 snippets

  • Array symmetric difference

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

    JavaScript, Array · Oct 22, 2020

  • Array unique symmetric difference

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

    JavaScript, Array · Oct 22, 2020

  • Mapped array difference

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

    JavaScript, Array · Oct 19, 2020