AI Hints
Home›JavaScript Tutorial›Sets, Maps and Regex
JavaScript · Lesson 109 of 138

Sets and Maps

Better collections.

⏱ 2 min read▶ Video at 2:11:06🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Arrays and objects cover most needs, but JavaScript has two more collections. A set holds unique values, with no duplicates. A map holds key value pairs, like an object, but any value can be a key, and it keeps its order.

Sets and Maps
From the video: Sets and Maps
  • Two more collections
  • Set: unique values
  • Map: any key

Set

A new set from an array drops the duplicates. Spreading it back into an array gives us the unique tags. Add, has, and size work as you'd expect. Has is very fast, even with millions of items. Run it.

app.jsjavascript
const tags = ["js", "web", "js", "node", "web", "js"];

const unique = new Set(tags);
console.log([...unique]);

unique.add("css");
unique.add("js");
console.log(unique.size, unique.has("node"), unique.has("python"));
Output
[ 'js', 'web', 'node' ]
4 true false

Map

A map stores pairs with set, and reads them with get. Here we count words, adding one to each count. Unlike an object, a map remembers the order things were added, and it has a size. And we can loop over its entries directly. Run it.

app.jsjavascript
const words = "the cat sat on the mat the end".split(" ");
const counts = new Map();

for (const w of words) {
  counts.set(w, (counts.get(w) ?? 0) + 1);
}

console.log(counts.get("the"), counts.size);
for (const [word, n] of counts) {
  if (n > 1) console.log(word, n);
}
Output
3 6
the 3

Summary

Sets hold unique values with fast lookups, and maps hold ordered key value pairs with any keys. Next, finding patterns in text with regular expressions.

Key takeaways
  • new Set(array)
  • map.set / map.get
  • has, size
Next up: Regular Expressions — patterns in text