Codiqo

Learn JavaScript · lesson 58 of 60 · about 7 minutes

Set

Keep a collection with no repeats and check quickly whether something is in it.

What you'll learn

  • Create a Set and use add, has and delete
  • Remove duplicates from an array
  • Combine and compare Sets

Every tag

Each of Sam's posts has its own tags, and some tags turn up on more than one post. Sam wants a list of every different tag, 4 tags: intro, loops, practice, arrays, and a way for visitors to follow the tags they like: followTags is what one visitor asked for, maybe with repeats, and the page answers Following loops, arrays (no posts about css). A Set keeps each tag once and can say straight away whether a tag is in it.

No repeats allowed

A Set holds values with no duplicates. Adding something that's already there does nothing.

set.add(x) puts a value in, set.has(x) checks for it, set.delete(x) takes it out and set.size counts them.

Using a Set

const seen = new Set();
seen.add("Ada");
seen.add("Bo");
seen.add("Ada");

console.log(seen.size);
console.log(seen.has("Bo"), seen.has("Cy"));

Output

2
true false

Removing duplicates

new Set(array) drops the repeats, and [...set] spreads it back into an array. Together they remove duplicates in one line, keeping the first time each value appeared.

Unique values, and what two lists share

const rolls = [3, 6, 3, 1, 6, 6];
console.log([...new Set(rolls)].join(","));

const mine = new Set(["tea", "cake", "jam"]);
const yours = new Set(["jam", "tea", "pie"]);
console.log([...mine].filter((x) => yours.has(x)).join(","));

Output

3,6,1
tea,jam

Tags without repeats

posts.flatMap((post) => post.tags) puts every post's tags into one array, and new Set(...) keeps each tag the first time it appears. [...new Set(followTags)] does the same for what the visitor asked for, so asking for loops twice follows it once. Then allTags.has(t) splits the asked-for tags into the ones Sam writes about and the ones Sam doesn't, yet.

Tip

set.has is much faster than array.includes on big collections, because a Set doesn't have to look through every item.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.