Array intersection

JavaScript, Array · Oct 20, 2020

Returns the elements that exist in both arrays, filtering duplicate values.

const intersection = (a, b) => {
  const s = new Set(b);
  return [...new Set(a)].filter(x => s.has(x));
};

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

More like this

  • JavaScript Array Set Operations

    Learn how to apply mathematical set operations to JavaScript arrays.

    Collection · 12 snippets

  • 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

  • Array intersection based on function

    Returns the elements that exist in both arrays, using a provided comparator function.

    JavaScript, Array · Oct 20, 2020

  • Pull values from array at index

    Mutates the original array to filter out the values at the specified indexes. Returns the removed elements.

    JavaScript, Array · Oct 22, 2020