IntersectionLoading saved progress…

Intersection

You've had to find the values shared between two or more lists — overlapping tags across articles, common interests between users, the set of products in stock at every warehouse. This is the set intersection operation, generalized to any number of arrays.

Implement intersection(...arrays). It accepts any number of array arguments and returns a new array containing the unique values that appear in every input array. The order of the returned values should follow their order in the first array.

Signature

function intersection(...arrays) {
  // returns a new array of unique values present in every input array.
  // intersection() with no arguments returns [].
}

Examples

intersection([1, 2, 3], [2, 3, 4], [3, 4, 5]);  // [3]
intersection([1, 2, 2, 3], [2, 3, 3]);          // [2, 3] — dedup the result
intersection(['a', 'b', 'c']);                  // ['a', 'b', 'c'] — one arg: unique of itself
intersection();                       // []
intersection([1, 2, 3], []);          // [] — anything ∩ ∅ is ∅
intersection([NaN, 1], [NaN, 2]);     // [NaN] — NaN equals itself here (SameValueZero)

Notes

  • Equality uses the SameValueZero algorithm — the same one Set and Array.prototype.includes use. NaN is treated as equal to NaN; +0 and -0 are treated as equal.
  • Uniqueness — the result contains no duplicates, even when the inputs do.
  • Order of the result follows the first array. intersection([3, 1, 2], [1, 2, 3]) returns [3, 1, 2], not [1, 2, 3].
  • No arguments — return []. Any empty array in the input — return [].
  • Don't mutate any input array. Return a new array.
Loading editor…