Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Array Intersection

Working With Arraysmedium

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Implement `intersection(a, b)` returning the unique values present in both arrays, in the order they first appear in `a`.

Sample tests

Input: intersection([1,2,3,4], [2,4,6])
Output: [2,4]
Input: intersection([1,2], [3,4])
Output: []

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Returning duplicates from a; dedupe a first.
  • Nested includes makes it quadratic; a Set is faster.

Learning resources

  • MDN: Array
Approach & explanation (try first)

A Set of b enables O(1) membership checks while you filter the deduplicated values of a.

Loading...
⌘/Ctrl + Enter

Run your code to see results.