Map and Set

Collect unique words in a Set and count them in a Map.

JavaScript · beginner · 6 min · 14 steps · free

What you'll learn

MapSet.js

const seen = new Set();
const counts = new Map();
const words = ['red', 'blue', 'red', 'green'];

for (const w of words) {
  seen.add(w);
  counts.set(w, (counts.get(w) ?? 0) + 1);
}

console.log(seen.size, [...seen]);
console.log(counts.get('red'), counts.has('pink'));

Step by step

  1. seen is created and points to a new Set: [].
  2. counts is created and points to a new Map: {}.
  3. words is created and points to a new Array: ["red", "blue", "red", "green"].
  4. A loop over w begins.
  5. seen.add("red"): the Set now holds red.
  6. counts.get("red") is undefined, so ?? 0 gives 0; the Map stores red → 1.
  7. w changes from "red" to "blue". "blue" is added to the end of the Set that seen points to.
  8. A new key blue with the value 1 is added to the Map that counts points to.
  9. "red" again: a Set ignores a value it already has.
  10. The Map's count for red goes up to 2.
  11. w changes from "red" to "green". "green" is added to the end of the Set that seen points to.
  12. A new key green with the value 1 is added to the Map that counts points to.
  13. w goes out of scope and disappears. It prints 3 [ 'red', 'blue', 'green' ].
  14. It prints 2 false.

Common mistakes

Best practices

Key takeaways

Check yourself

new Set([1, 1, 2]).size?

Answer: 2

map.get("missing")?

Answer: undefined

·

More in Objects and Arrays