CodeOath
← All posts
JavaScript60 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Part 12 of 16 · ~2 min

Map and Set: When a Plain Object Isn't Enough

For simple cases, a plain object does the job fine as a place to stash key-value pairs. Map and Set earn their keep once that stops being true.

const byId = new Map(candidates.map(c => [c.id, c]));

byId.get("c3").name; // "Amara Chen" — direct lookup, no scanning the array
byId.has("c6");       // false
byId.size;             // 5 — a real property, not a method call like Object.keys(obj).length

for (const [id, candidate] of byId) { // Map is directly iterable, in INSERTION order
  console.log(id, candidate.name);
}

Building byId once turns "find the candidate with this id" from an O(n) scan through candidates.find(...) into an O(1) lookup — worth doing the moment you're looking things up by id more than once.

QuestionPlain objectMap
What's allowed as a key?Only a string or a Symbol — anything else gets silently turned into a string firstAnything at all — an object, a function, even another Map
How do you find out how many entries there are?Count them: Object.keys(obj).lengthJust ask: .size
What order do entries come back in?Roughly insertion order, except keys that look like array indices jump ahead of everything else, sorted numericallyExactly the order they went in, with no special-case reshuffling
Can you loop over it directly?Not without going through Object.entries() or similar firstYes — hand it straight to for...of
Any risk of a key stepping on something the language already defined?Yes — a candidate id that happened to be the literal string "constructor" would land on a property Object.prototype already owns, confusing a careless for...in or .hasOwnProperty checkNo — a Map's keys live in their own storage, entirely outside any prototype chain

A Set keeps at most one copy of any given value, checked with that same SameValueZero comparison .includes() relies on — which is exactly what makes it the natural tool for stripping duplicates out of an array. Every distinct skill tag across the whole candidate pool, say:

const allTags = candidates.flatMap(c => c.tags); // 10 tags total, with repeats
const uniqueTags = [...new Set(allTags)];
// ["node", "postgres", "react", "css", "redis", "typescript"] — 6 unique