Lesson 8 of 8

Intersection and difference

Goal

From n×m down to n+m

01

Explanation

“Who signed up for both courses?” and “Who signed up only for the first one?” come up again and again in different forms: shared tags, deleted IDs, missing permissions.

The first solution that comes to mind is a.filter(x => b.includes(x)), which scans all of b for every item in a, so with a thousand items in each you need a million comparisons. It's better to build a Set from b once and then call has for each item, which takes two thousand steps instead of a million.

A common mistake is building the set inside the function you pass to filter. The code a.filter(x => new Set(b).has(x)) builds a new set for every item, which makes it even slower than includes.

02

Your task

Write intersect(a, b) to return the items found in both arrays, and difference(a, b) to return what's in a but not in b. Both functions must keep the order of a and read b only once.

Checks

6 checks
  1. intersect returns the shared items
  2. intersect keeps the order of the first array
  3. difference returns what's only in the first array
  4. Empty arrays don't cause errors in either function
  5. intersect reads the second array only once
  6. difference reads the second array only once
03

Hints

0/3
Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.