Mapped array difference

JavaScript, Array · Oct 19, 2020

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

const differenceBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.map(fn).filter(el => !s.has(el));
};

differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [2]

More like this

  • JavaScript Array Set Operations

    Learn how to apply mathematical set operations to JavaScript arrays.

    Collection · 12 snippets

  • 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

  • Mapped array intersection

    Returns the elements that exist in both arrays, after applying the provided function to each array element of both.

    JavaScript, Array · Oct 20, 2020

  • Mapped array union

    Returns every element from both arrays that exists at least once after applying the provided function.

    JavaScript, Array · Oct 22, 2020