Skip to content

JavaScript Tutorial Map, Set and Other Collections

Practical Collection Examples

Lesson 189 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Four small, realistic uses of Map and Set.

1. Counting how often things appear

script.js
JS
const text = "the quick brown fox jumps over the lazy dog the end";
const counts = new Map();

for (const word of text.split(" ")) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}

const mostCommon = [...counts].sort((a, b) => b[1] - a[1])[0];
console.log(mostCommon); // → ["the", 3]

2. Grouping items

script.js
JS
const products = [
  { name: "Pen", category: "stationery" },
  { name: "Mug", category: "kitchen" },
  { name: "Notebook", category: "stationery" }
];

const byCategory = new Map();
for (const product of products) {
  if (!byCategory.has(product.category)) byCategory.set(product.category, []);
  byCategory.get(product.category).push(product.name);
}

console.log(byCategory);
// → Map(2) { 'stationery' => ['Pen', 'Notebook'], 'kitchen' => ['Mug'] }

3. Unique values and quick lookups

script.js
JS
const emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com"];
const unique = [...new Set(emails)];
console.log(unique.length); // → 3

const blocked = new Set(["c@x.com"]);
console.log(unique.filter(email => !blocked.has(email))); // → ["a@x.com", "b@x.com"]

4. Memoising (caching) a function

script.js
JS
function memoize(fn) {
  const cache = new Map();
  return function (arg) {
    if (cache.has(arg)) {
      console.log("from cache");
      return cache.get(arg);
    }
    const result = fn(arg);
    cache.set(arg, result);
    return result;
  };
}

const square = memoize(n => n * n);
console.log(square(9)); // → 81
console.log(square(9)); // → 81  (and "from cache" is printed)

5. Tracking selected items on a page

index.html
HTML
<ul id="list">
  <li data-id="1">Apple</li>
  <li data-id="2">Banana</li>
  <li data-id="3">Cherry</li>
</ul>
<p id="out">Selected: none</p>
<script>
  const selected = new Set();

  document.querySelector("#list").addEventListener("click", event => {
    const li = event.target.closest("li");
    if (!li) return;

    const id = li.dataset.id;
    selected.has(id) ? selected.delete(id) : selected.add(id);
    li.style.fontWeight = selected.has(id) ? "bold" : "normal";

    document.querySelector("#out").textContent = "Selected: " + ([...selected].join(", ") || "none");
  });
</script>

A Set fits perfectly: an item is either selected or not, and there are no duplicates.

Choosing a structure

NeedUse
Ordered list that may repeatArray
Record with known fieldsObject
Lookup by any key, counting, groupingMap
Unique values, fast hasSet
Attach data to objects without leaksWeakMap / WeakSet