Summary - Map and Set
Build a word counter app using Map and Set.
Summary - Map and Set
In this group you learned Map for an ordered collection that accepts any key type, and Set for a collection of unique values. You manage both with set/get/has/delete and size.
WeakMap and WeakSet hold object references weakly so the garbage collector can reclaim them; they cannot be iterated. Map is faster than Object for frequent add/remove of key-value pairs and guarantees insertion order. Now you will combine them in a word counter.
Exercise Word counter app
Split a sentence string by spaces. Count how many times each word appears in a Map called counts; use counts.get(word) || 0 to read the current value. Then collect the unique words into a Set called uniqueWords and log how many unique words there are with console.log.
Show example solution
const sentence = "apple pear apple banana pear apple";
const words = sentence.split(" ");
const counts = new Map();
const uniqueWords = new Set();
for (const word of words) {
counts.set(word, (counts.get(word) || 0) + 1);
uniqueWords.add(word);
}
console.log(uniqueWords.size);
Test yourself
-
Which scenario is the best fit for Set?
- Attach temporary metadata to an object
- Store a user's roles by id
- Find unique cities from a list
- Hold fixed-shape user data
Show answer
Find unique cities from a list — Correct. Set filters out duplicates automatically; ideal for unique cities.
-
Complete the word counter in one line
const counts = new Map(); const word = "apple"; counts.set(word, (counts.get(word) || 0) + ____); console.log(counts.get(word));Show answer
const counts = new Map(); const word = "apple"; counts.set(word, (counts.get(word) || 0) + 1); console.log(counts.get(word)); -
Match the collections
- Map
- Key-value, ordered
- Set
- Unique values
- WeakMap
- Object keys, GC friendly
- Object
- Fixed shape, prototype chain