Index counts and membership using Map and Set
Quick answer
A frequency table maps a value to its count, while a set records membership without multiplicity. They avoid repeated scanning when many lookups are needed.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const counts=new Map();for(const label of ["pen","box","pen","pen"])counts.set(label,(counts.get(label)??0)+1);console.log(JSON.stringify([...counts]));Expected console output:
[["pen",3],["box",1]]Each repeated label increments the existing count.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const a={id:1},b={id:1};const objects=new Set([a,b,a]);const ids=new Set([a.id,b.id]);console.log(objects.size,ids.size,new Map([[1,"n"],["1","s"]]).size);Expected console output:
2 1 2Object identity and primitive type determine key equality.
How it works and cost model
Increment a Map count with counts.set(key,(counts.get(key) ?? 0)+1), assuming all stored values are counts. Set.add and Set.has record membership; objects compare by identity, not structural content. For a table of n items and d distinct keys, storage O(d). Under typical hash-table assumptions, n updates take expected O(n), but ECMAScript only requires average access time sublinear in collection size, not a specific hash table or universal O(1). Choose a canonical primitive ID when logically identical records must share a key.
Common mistakes
Do not use Set when you need counts. Do not treat two freshly created equal-looking objects as the same Map key.
Practice
Count the labels ["pen","box","pen","pen"], then find unique labels in encounter order. Repeat with a numeric key and a string key.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Index counts and membership using Map and Set — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
Which structure retains how many times a key appeared?
Why use canonical product IDs instead of object keys for logical product identity?
What access complexity does ECMAScript require for Map and Set on average?
What is the exact console output in the Frequency map example 1?
const counts=new Map();for(const label of ["pen","box","pen","pen"])counts.set(label,(counts.get(label)??0)+1);console.log(JSON.stringify([...counts]));What is the exact console output in the Frequency map example 2?
const a={id:1},b={id:1};const objects=new Set([a,b,a]);const ids=new Set([a.id,b.id]);console.log(objects.size,ids.size,new Map([[1,"n"],["1","s"]]).size);