Unique values, lookups & counting

Maps and Sets

Lesson 5 of 20 · 10 min · Module 2: Work with collections

Arrays are great for ordered lists, but checking "have I seen this?" in an array gets slow. Set and Map answer such questions instantly, at any size.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Track unique values with a Set
  • Count and look up with a Map
  • Convert between Maps, Sets and arrays

The idea

A Set stores unique values: set.add(x), set.has(x). A Map stores pairs: map.set(key, value), map.get(key). Both keep insertion order and can be turned into arrays with [...set] or [...map].

const seen = new Set(["a", "b", "a"]);
console.log(seen.size, [...seen]);

01Fast membership

set.has(x) takes the same time whether the Set holds ten values or a million. array.includes(x) has to look at every element.

02Maps keep key types

In a plain object, the keys 1 and "1" are the same property. In a Map they are different keys, which keeps counts accurate.

const m = new Map([[1, "number"], ["1", "string"]]);
console.log(m.size, m.get(1));
Output
2 number

03Back to arrays

[...map] gives [key, value] pairs, and Object.fromEntries(map) gives a plain object when you need JSON. new Set(array) is the shortest way to remove duplicates.

Your turn

Write uniqueBy(items, keyFn) that keeps only the first item for each key returned by keyFn, in order. Write countBy(items, keyFn) that returns a Map from each key to how many items had it, in order of first appearance.

What the checks look for

  • Keeps the first item for each key
  • Works with computed keys
  • countBy returns a Map with counts in order
  • countBy keeps keys of any type
Try it in the editor →

Take this with you

Reach for Set to ask "seen it?" and Map to ask "what belongs to this key?".

Go a little further

Write groupBy(items, keyFn) that returns a Map from each key to the array of its items.

Learn JavaScript Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →