Typorithm · medium

Set

set-operationscollectionssetdedupmembership
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Set

0%

Objects & Maps

A Set stores unique values: new Set(arr) deduplicates, has gives O(1) membership, and add/delete mutate it. Spread back to an array with [...s], and build union and intersection with spread and filter.

A Set holds each value at most once, so new Set(array) is the idiomatic one-liner for removing duplicates.

Membership with set.has(x) is O(1), far faster than array.includes on large data, and add/delete keep the Set up to date.

Sets are not arrays — spread with [...set] to get an array back — and you compose them: union is new Set([...a, ...b]) while intersection is new Set([...a].filter((x) => b.has(x))).

01

new Set(arr) deduplicates values.

02

has, add, and delete are O(1) operations.

03

Spread + filter build union and intersection.

const unique = new Set([1, 2, 2, 3])
const present = unique.has(2)
unique.add(4)
unique.delete(1)
const arr = [...unique]
const a = new Set([1, 2, 3])
const b = new Set([2, 3, 4])
const union = new Set([...a, ...b])
const intersection = new Set([...a].filter((x) => b.has(x)))

Read the implementation

Connect each part of the code to the concept before you type.

1. Dedup with Set

Passing an array to new Set drops duplicates, keeping each value once.

new Set([1, 2, 2, 3])

2. Membership test

has(value) is an O(1) check for whether the value is in the Set.

unique.has(2)

3. add a value

add inserts a value; adding an existing value is a no-op.

unique.add(4)

4. delete a value

delete removes a value and returns whether it was present.

unique.delete(1)

5. Back to array

Spreading a Set into an array is the standard way to materialize its values.

[...unique]

6. Union

Spreading both Sets into one new Set yields their union with duplicates removed.

new Set([...a, ...b])

7. Intersection

Filtering a's values by b.has keeps only the values present in both Sets.

new Set([...a].filter((x) => b.has(x)))

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Set: Lesson & Practice · Typorithm | ApplyDjinn