Home › Learn › JavaScript › Objects

Map and Set

Lesson 25 of 40. Keyed collections and unique collections.

A Map is a dictionary whose keys can be anything, kept in insertion order: map.set(key, value), map.get(key) (undefined when missing), map.has(key), map.delete(key), map.size, and for (const [k, v] of map). Plain objects also work as dictionaries with string keys; a Map is cleaner when keys are not fixed names, and it never collides with built-in properties.

A Set keeps each value once: set.add(x), set.has(x), set.size. new Set(array) removes duplicates and [...set] turns it back into an array. has is fast even for large sets.

const counts = new Map();
for (const w of ["a", "b", "a"]) counts.set(w, (counts.get(w) ?? 0) + 1);
console.log(counts.get("a"));          // 2
console.log([...new Set([1, 1, 2])]);  // [1, 2]

Your task

Write wordCounts(text) returning a Map from each lower-cased word to how often it appears, unique(items) returning an array of the distinct items in first-seen order, and hasDuplicates(items).

Hint 1

for (const w of text.toLowerCase().split(/\s+/)) counts.set(w, (counts.get(w) ?? 0) + 1);

Hint 2

[...new Set(items)] and new Set(items).size !== items.length

Show the solution
function wordCounts(text) {
  const counts = new Map();
  for (const w of text.toLowerCase().split(/\s+/)) {
    if (w) counts.set(w, (counts.get(w) ?? 0) + 1);
  }
  return counts;
}

function unique(items) {
  return [...new Set(items)];
}

function hasDuplicates(items) {
  return new Set(items).size !== items.length;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.