Array set operations
Back in Phase 4 you used .filter() to narrow an array down by a condition.
The condition can just as easily be "is this missing from another array?" -
a.filter((item) => !b.includes(item)) keeps only the items of a that
b doesn't have, which is exactly what a set difference is.
For duplicates, JavaScript's built-in Set does the work for you: a Set
can only ever hold one copy of each value, and it remembers the order things
were added in. Spread an array into a Set and back into an array -
[...new Set(arr)] - and you've deduplicated it in one line, first
occurrence kept, order preserved.
Your task: write diff(a, b), returning the items in array a that are
NOT in array b, and dedupe(arr), returning arr with duplicates removed,
keeping the order items first appeared in.
You'll practice:
Filtering one array against the contents of another
Deduplicating an array with a Set
Show a hint
Show solution
Related reading: Maps & Sets - Lookup by Key →
Previous Next