Iterating Sets and Maps
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Looping Through a Set
Suppose you want to display every Codémon in your Codédex one by one. Even though a Set has no index numbers (like `codedex[0]`), you can loop through its values directly using a `for...of` loop—just like you do with an array:
const codedex = new Set(["Zap", "Aquachu", "Pyrochu"]);
for (const name of codedex) {
console.log("- " + name);
}A Set also has a built-in `.forEach()` method that runs a callback function for each value in the Set:
const codedex = new Set(["Zap", "Aquachu"]);
codedex.forEach((name) => {
console.log(name.toUpperCase());
});Keep in mind that Sets do not have `.map()`, `.filter()`, or `.reduce()`. We'll see how to use those on a Set in just a moment!
Exercise 2 — Looping Through a Map
Because a Map stores key-value pairs, looping over a Map with `for...of` gives you a two-item array `[key, value]` on each step. You can unpack both variables right inside the loop header using array destructuring (`[name, score]`):
const scores = new Map([
["Sam", 120],
["Lea", 340]
]);
for (const [name, score] of scores) {
console.log(name + ": " + score);
}You can also use `.forEach()` on a Map, but watch out for the parameter order: `.forEach((value, key) => ...)` passes the value first and the key second (just like array `.forEach((item, index) => ...)`):
const scores = new Map([
["Sam", 120],
["Lea", 340]
]);
scores.forEach((score, name) => {
console.log(name + " has " + score + " pts");
});Exercise 3 — Getting Only the Keys or Only the Values
Sometimes you only need the keys or only the values from a Map: - `map.keys()` gives you all the keys. - `map.values()` gives you all the values. Use the spread operator (`[... ]`) to turn either one into a regular array:
const scores = new Map([
["Sam", 120],
["Lea", 340]
]);
console.log([...scores.keys()]);
console.log([...scores.values()]);Once you have an array, you can use any array method on it—such as `.reduce()` to add up all the scores:
const scores = new Map([
["Sam", 120],
["Lea", 340]
]);
const total = [...scores.values()].reduce((sum, n) => sum + n, 0);
console.log("Total: " + total);Exercise 4 — Quiz: How Many Lines?
How many lines does this code print?
const s = new Set(["a", "b", "a", "c"]);
for (let v of s) {
console.log(v);
}3412Hint : A Set never holds the same value twice.
Exercise 5 — Quiz: The forEach Order
What does this code print?
const m = new Map([["a", 1]]);
m.forEach((x, y) => console.log(x + " " + y));1 aa 1a a1 1Hint : On a Map, the callback does not receive the key first.
Exercise 6 — Print Every Pair
Print each trainer with their score.
Hint : The first slot of the pair matches what the body prints, and the loop keyword is the one used for values.
Exercise 7 — Using Array Methods on a Set or Map
Here is the golden rule when working with Sets and Maps: - To simply loop through entries, `for...of` or `.forEach()` works directly. - To transform or filter entries with `.map()`, `.filter()`, or `.reduce()`, convert the collection into an array first with `[... ]`:
const codedex = new Set(["Zap", "Aquachu", "Pyrochu"]);
const longNames = [...codedex].filter((name) => name.length > 3);
console.log(longNames);Spreading a Map (`[...scores]`) creates an array of `[key, value]` pairs, which you can destructure right inside `.map()` or `.filter()`:
const scores = new Map([
["Sam", 120],
["Lea", 340]
]);
const summary = [...scores].map(([name, score]) => name + " (" + score + ")");
console.log(summary.join(" / "));Exercise 8 — Total the Scores
Add up every score of the Map.
Hint : You need one side of the pairs, then the method that boils a list down to one number.
Exercise 9 — Iteration Cheat Sheet
Match each expression with what it gives.
for (let v of mySet)for (let [k, v] of myMap)[...myMap.keys()]myMap.forEach((v, k) => ...)Exercise 10 — Codédex Report
Print a full report from a Set of caught Codémon and a Map of their levels.
Step 1: print `"Caught: N"` with the size of the Set, then each name on its own line with `"- "` in front. Step 2: print `"Long names: N"` with the number of names longer than 3 characters. Step 3: for each pair of the Map, print `"name is level X"`. Step 4: print `"Total level: N"` with the sum of the values, and `"Highest: N"` with the biggest level.
Expected output:
Caught: 3
- Zap
- Aquachu
- Metachu
Long names: 2
Zap is level 4
Aquachu is level 12
Metachu is level 20
Total level: 36
Highest: 20const caught = new Set(["Zap", "Aquachu", "Metachu"]);
const levels = new Map([
["Zap", 4],
["Aquachu", 12],
["Metachu", 20]
]);
// Write your code here