Use a Map when you need a reusable frequency table from an array. Each distinct value becomes a key, and its stored number increases every time the value appears. This avoids mixing the counting logic with console output or page rendering.
Last updated: October 3, 2026.
function countValues(values) {
const counts = new Map();
for (const value of values) {
counts.set(value, (counts.get(value) ?? 0) + 1);
}
return counts;
}
const counts = countValues(['red', 'blue', 'red', 'green', 'blue', 'red']);
console.log(counts.get('red')); // 3
console.log(Object.fromEntries(counts));
// { red: 3, blue: 2, green: 1 }The function returns data instead of printing it, so the caller can query one count, loop over every entry, render a table, or serialize the result. The nullish coalescing operator supplies zero only when a key has not been counted yet.
Keep a Map when keys are not just strings
A JavaScript Map accepts strings, numbers, objects, and other values as distinct keys. It also preserves the order in which keys first appeared. MDN’s Map reference documents those properties.
For object values, identity matters: two separate objects with identical fields are still two different keys. If records should be grouped by a property such as product.id, pass that property to the counter instead of the entire object.
Convert only at the output boundary
A plain object is convenient for templates and JSON when every key is a safe string. Object.fromEntries() converts the map’s key-value pairs without repeating the counting work. Keep the Map when keys include objects or when key types must remain distinct.
For related collection patterns, review JavaScript arrays, loops and iteration, and reusable functions.