Summary - Map and Set
- JavaScript course
- Advanced
- Lesson 41/100
- 5 min
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.
Practice 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.
Starter code
const sentence = "apple pear apple banana pear apple";
// Split the sentence by spaces
// Count each word in a Map called counts (use counts.get(word) || 0)
// Collect unique words into a Set called uniqueWords
// Log the number of unique words to the consoleSample 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);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- Hold fixed-shape user data
Explanation: Set filters out duplicates automatically; ideal for unique cities.
2 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));
const counts = new Map();
const word = "apple";
counts.set(word, (counts.get(word) || 0) + 1);
console.log(counts.get(word));
Explanation: You bump the existing count by one.
3 Match the collections
| Term | Meaning |
|---|---|
Map |
Key-value, ordered |
Set |
Unique values |
WeakMap |
Object keys, GC friendly |
Object |
Fixed shape, prototype chain |