Sub topic 5
Iterating Maps: keys, values, entries, and forEach
This chapter assumes you can create a Map and use set, get, has, and delete. It also assumes you know for...of loops, array destructuring, and the spread operator.
Insertion Order Is Guaranteed
A Map remembers the order in which each key was first added. Every way of iterating a Map follows that order. Plain objects work differently: they put integer-like keys first and sort them numerically, so a key such as '10' can jump ahead of keys you added earlier.
The order rules for a Map are short:
- Calling
seton an existing key changes its value and leaves the key where it is. - Deleting a key and then adding it again moves that key to the end.
const scores = new Map([['ana', 90], ['ben', 75], ['cy', 82]]);
scores.set('ana', 95); // update: 'ana' stays first
scores.delete('ben');
scores.set('ben', 80); // re-insert: 'ben' moves to the end
console.log([...scores.keys()]); // ['ana', 'cy', 'ben']The Three Iterator Methods
Each of these methods returns an iterator, which is an object you can loop over once with for...of or spread into an array.
| Method | Yields | Example item |
|---|---|---|
| `keys()` | each key | `'ana'` |
| `values()` | each value | `95` |
| `entries()` | `[key, value]` arrays | `['ana', 95]` |
A Map is iterable by itself, and its default iterator is entries(). That is why for (const [k, v] of map) works without calling any method.
const stock = new Map([['apples', 12], ['pears', 0], ['plums', 7]]);
for (const item of stock.keys()) {
console.log(item); // apples, pears, plums
}
let total = 0;
for (const count of stock.values()) {
total += count;
}
console.log(total); // 19
for (const [item, count] of stock) {
if (count === 0) console.log(`${item} sold out`); // pears sold out
}
console.log(stock[Symbol.iterator] === stock.entries); // trueforEach and Its Argument Order
forEach calls your callback once per entry. The callback receives the value first, then the key, then the Map. This matches Array.prototype.forEach, where the element comes before the index. People who expect (key, value) get this wrong often.
const stock = new Map([['apples', 12], ['plums', 7]]);
stock.forEach((value, key) => {
console.log(`${key}: ${value}`); // apples: 12, plums: 7
});Common Errors with Iterators
Iterators can be used only once. After an iterator has been consumed, it yields nothing more.
const m = new Map([['a', 1], ['b', 2]]);
const it = m.keys();
console.log([...it]); // ['a', 'b']
console.log([...it]); // []If you need to go through the keys again, call m.keys() again or store the result as an array.
Iterators are live. The loop sees changes to the Map that happen while it runs. An entry added during the loop is visited later in that same loop, and an entry deleted before the loop reaches it is skipped. If you write a loop that adds an entry on every pass, it never ends. To change a Map safely while looping, loop over a copy instead: for (const [k, v] of [...m]).
Arrays need conversion first. Iterators do not have array methods like map or filter. Spread them into an array first, for example [...m.values()].filter(...). Later chapters cover more conversions.
Exercise
What does this code print? const m = new Map([['x', 1], ['y', 2]]); m.set('x', 10); m.delete('y'); m.set('z', 3); m.set('y', 4); m.forEach((a, b) => console.log(a, b));
Show answer
It prints "10 x", then "3 z", then "4 y". Updating 'x' keeps it in first place. Deleting 'y' and adding it again moves it to the end, after 'z'. The callback's first parameter (a) holds the value and the second (b) holds the key.
Exercise
You need the names of all items whose count is above 5 from the Map stock, stored as an array. Write one expression that produces it.
Show answer
[...stock].filter(([, count]) => count > 5).map(([name]) => name). Spreading the Map produces an array of [key, value] pairs, which you can then filter and map like any other array.