Sikau

Advanced JavaScript · Day 12 · about 20 min

Set

Collections with no duplicates.

Each thing once

Tags on a post, students who attended, unique visitors — you often want each value only once. A Set keeps unique values and checks membership instantly.

Using a Set

const tags = new Set(["js", "web", "js", "css"]);
console.log(tags.size);
tags.add("web");
tags.add("node");
console.log(tags.has("css"));
tags.delete("css");
console.log([...tags]);

const unique = [...new Set([3, 1, 3, 2, 1])];
console.log(unique);
const morning = new Set(["Asha", "Bikash", "Chandra"]);
const evening = new Set(["Bikash", "Dawa"]);

const both = [...morning].filter((n) => evening.has(n));
const either = new Set([...morning, ...evening]);
const onlyMorning = [...morning].filter((n) => !evening.has(n));
console.log(both, either.size, onlyMorning);

The rest of this lesson

  • Why sets are fastexplain
  • Set operationsexplain
  • Predict the outputpredict
  • Unique valuespredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript