Sets and Maps
Better collections.
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.

- 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.
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"));[ '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.
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);
}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