JavaScript Set and Map: Unique Values, Key-Value Collections, Set Methods and When to Use Them
Set and Map in depth: adding, checking and deleting, SameValueZero equality and object identity, insertion-order iteration, the ES2025 set methods (union, intersection, difference), counting and grouping with Map and Map.groupBy, ES2026 getOrInsert, JSON conversion, and Map vs plain objects.
kvi5hnuCode Sprout team member6 min readOn this page
Arrays and objects can do almost anything, but two jobs come up so often that JavaScript has dedicated classes for them:
Set: a collection of unique values. Asking "is this value in the set?" is fast, however big the set is.Map: a collection of key-value pairs where keys can be any value (objects, numbers, booleans), not just strings.
This article opens Part 11, a tour of JavaScript's standard library.
Set
const tags = new Set(["js", "css"]);
tags.add("html").add("js"); // add returns the set, so calls chain; "js" is already there
console.log(tags, tags.size);
console.log(tags.has("css"), tags.has("CSS"));
console.log(tags.delete("css"), tags.delete("css"), tags.size);
tags.clear();
console.log(tags.size);
Set(3) { 'js', 'css', 'html' } 3
true false
true false 2
0
new Set(iterable)accepts any iterable: an array, a string, another set, a map's keys.add(value)returns the set; adding an existing value does nothing.delete(value)returnstrueif the value was there.sizeis a property, not a method (and notlength).
Removing duplicates
The most common one-liner with sets:
const visits = ["home", "cart", "home", "help", "cart"];
console.log([...new Set(visits)]);
console.log(Array.from(new Set("banana")).join(""));
[ 'home', 'cart', 'help' ]
ban
Duplicates are dropped and the first occurrence's order is kept.
How a Set compares values
Sets use SameValueZero equality: like ===, except NaN equals NaN (and 0 equals -0). For objects, that means identity: two different objects with the same contents are different members:
const s = new Set([1, "1", NaN, NaN, 0, -0]);
console.log([...s]);
const point = [1, 2];
s.add(point);
console.log(s.has([1, 2]), s.has(point));
[ 1, '1', NaN, 0 ]
false true
1 and "1" are different values; NaN is stored once. [1, 2] written again creates a new array, so it isn't found. To store values by content, use a key you build yourself, such as s.add(JSON.stringify(point)) or `${x},${y}`.
Iterating a set
Sets remember insertion order and are iterable:
const primes = new Set([2, 3, 5, 7]);
let sum = 0;
for (const p of primes) sum += p;
console.log(sum, Math.max(...primes), [...primes].filter((p) => p > 2));
primes.forEach((value, sameValue) => {
if (value === 2) console.log(value, sameValue);
});
17 7 [ 3, 5, 7 ]
2 2
forEach passes the value twice (as "value" and "key") so its callback signature matches Map's. Sets have no indexes: there's no primes[0]. Convert to an array when you need position, sorting or array methods.
Why Set is faster than an array for lookups
array.includes(x) checks elements one by one, so its time grows with the array's length. set.has(x) uses a hash table and takes roughly constant time. For a few elements it doesn't matter; for thousands of lookups against thousands of items, it's the difference between instant and slow:
const banned = new Set(["spam@x.com", "bot@y.com"]);
const signups = ["ana@a.com", "bot@y.com", "bo@b.com"];
console.log(signups.filter((email) => !banned.has(email)));
[ 'ana@a.com', 'bo@b.com' ]
Set methods (ES2025)
Sets now have built-in methods for the classic set operations. Each returns a new set and leaves the original unchanged:
const frontend = new Set(["html", "css", "js"]);
const backend = new Set(["js", "sql", "go"]);
console.log(frontend.union(backend));
console.log(frontend.intersection(backend));
console.log(frontend.difference(backend));
console.log(frontend.symmetricDifference(backend));
Set(5) { 'html', 'css', 'js', 'sql', 'go' }
Set(1) { 'js' }
Set(2) { 'html', 'css' }
Set(4) { 'html', 'css', 'sql', 'go' }

And three methods that answer yes/no questions:
const skills = new Set(["html", "css", "js"]);
console.log(new Set(["js"]).isSubsetOf(skills)); // every member of the left is in skills
console.log(skills.isSupersetOf(new Set(["css"]))); // skills contains all of the right
console.log(skills.isDisjointFrom(new Set(["sql"]))); // nothing in common
true
true
true
The argument must be "set-like" (it needs size, has and keys), so another Set or a Map works, but a plain array doesn't: convert it first with new Set(array). Before ES2025 you'd write these with spread and filter, for example new Set([...a].filter((x) => b.has(x))) for an intersection, which you'll still see in older code.
Map
const scores = new Map([
["ana", 3],
["bo", 5],
]);
scores.set("cy", 1).set("ana", 4); // set chains; an existing key gets a new value
console.log(scores, scores.size);
console.log(scores.get("ana"), scores.get("zed"), scores.has("bo"));
console.log(scores.delete("bo"), scores.size);
Map(3) { 'ana' => 4, 'bo' => 5, 'cy' => 1 } 3
4 undefined true
true 2
new Map(iterable) takes [key, value] pairs: an array of arrays, another map, or Object.entries(obj).
Any value can be a key
This is Map's main advantage over plain objects, whose keys are always strings or symbols:
const ana = { id: 1 };
const bo = { id: 2 };
const lastSeen = new Map();
lastSeen.set(ana, "09:15").set(bo, "10:40");
console.log(lastSeen.get(ana), lastSeen.get({ id: 1 }));
const asObject = {};
asObject[ana] = "09:15";
asObject[bo] = "10:40"; // both keys become "[object Object]"
console.log(Object.keys(asObject), asObject[ana]);
09:15 undefined
[ '[object Object]' ] 10:40
Map keys use the same SameValueZero comparison as sets: objects by identity, and NaN works as a key. Using objects as keys lets you attach data to objects (DOM elements, users, requests) without modifying them.
Iterating a map
Maps iterate in insertion order, yielding [key, value] pairs, which destructure nicely:
const stock = new Map([["apples", 12], ["pears", 0], ["plums", 7]]);
for (const [fruit, count] of stock) {
if (count > 0) console.log(fruit, count);
}
console.log([...stock.keys()], [...stock.values()]);
stock.forEach((count, fruit) => { // value first, then key
if (count === 0) console.log("out of", fruit);
});
apples 12
plums 7
[ 'apples', 'pears', 'plums' ] [ 12, 0, 7 ]
out of pears
keys(), values() and entries() return iterators (spread them into arrays for array methods). Note forEach's argument order: value, then key, matching array.forEach(element, index).
Counting and grouping
Counting occurrences is a classic Map job:
const words = "to be or not to be".split(" ");
const counts = new Map();
for (const w of words) {
counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(counts);
const [topWord, topCount] = [...counts].sort((a, b) => b[1] - a[1])[0];
console.log(topWord, topCount);
Map(4) { 'to' => 2, 'be' => 2, 'or' => 1, 'not' => 1 }
to 2
To group items, Map.groupBy (ES2024) does the whole loop for you; its callback returns each item's group key, which can be any value:
const people = [
{ name: "Ana", team: "red" },
{ name: "Bo", team: "blue" },
{ name: "Cy", team: "red" },
];
const byTeam = Map.groupBy(people, (person) => person.team);
console.log(byTeam.get("red").map((p) => p.name), byTeam.size);
[ 'Ana', 'Cy' ] 2
Object.groupBy is the same but returns a plain (null-prototype) object, which is fine when group keys are strings.
getOrInsert (ES2026)
The "get the value, or insert a default first" pattern is so common that ES2026 added two methods for it:
const groups = new Map();
groups.getOrInsert("red", []).push("Ana"); // inserts [] the first time
groups.getOrInsert("red", []).push("Cy"); // reuses the existing array
groups.getOrInsertComputed("blue", () => []).push("Bo"); // default computed only if missing
getOrInsertComputed calls its function only when the key is missing, so it suits expensive defaults. These are new: they're in recent Firefox and Safari releases but not yet in every browser or in Node 25, so check support or use the has/set version:
const groups = new Map();
function getOrInsert(map, key, defaultValue) {
if (!map.has(key)) map.set(key, defaultValue);
return map.get(key);
}
getOrInsert(groups, "red", []).push("Ana");
getOrInsert(groups, "red", []).push("Cy");
console.log(groups);
Map(1) { 'red' => [ 'Ana', 'Cy' ] }
Converting and serializing
JSON.stringify doesn't understand maps and sets; it turns both into {}. Convert them first:
const prefs = new Map([["theme", "dark"], ["size", 14]]);
const tags = new Set(["a", "b"]);
console.log(JSON.stringify(prefs), JSON.stringify(tags));
console.log(JSON.stringify(Object.fromEntries(prefs)), JSON.stringify([...tags]));
const restored = new Map(Object.entries(JSON.parse('{"theme":"dark","size":14}')));
console.log(restored.get("size"));
{} {}
{"theme":"dark","size":14} ["a","b"]
14
Object.fromEntries(map) and new Map(Object.entries(obj)) convert between maps and objects (when keys are strings). structuredClone copies maps and sets deeply.
Map or object? Set or array?
| Use a Map when... | Use a plain object when... |
|---|---|
| keys aren't strings (objects, numbers you don't want converted) | the shape is fixed and known (a record like { name, age }) |
| keys are added and removed often, at runtime | you need JSON directly |
| you need the size or insertion order reliably | you're writing config, options or API data |
keys come from users (no risk of __proto__ or toString clashes) | you want destructuring and dot access |
| Use a Set when... | Use an array when... |
|---|---|
| values must be unique | duplicates are meaningful |
| you check membership often | you need indexes, sorting or position |
| you need union/intersection/difference | you mostly iterate or transform |
Common questions
Why doesn't set.has([1, 2]) find an array I added?
Sets compare objects by identity. [1, 2] creates a new array each time it's written. Keep a reference to the original, or store a primitive key built from the contents.
Are Sets ordered?
Yes, by insertion order: iteration always returns members in the order they were first added. They're not indexed, though, and re-adding an existing member doesn't move it.
Can I use map[key] instead of map.get(key)?
No. map.key = value creates an ordinary property on the Map object, not an entry; get, has, size and iteration ignore it. Always use get and set.
How do I sort a Map?
Maps keep insertion order and can't be sorted in place. Build a new one from sorted entries: new Map([...map].sort((a, b) => a[1] - b[1])).
Summary
Setstores unique values with fasthas;new Set(array)removes duplicates while keeping first-seen order.Mapstores key-value pairs with any value as a key; useget,set,has,delete,size.- Both compare with SameValueZero (objects by identity,
NaNequal to itself) and iterate in insertion order. - ES2025 Set methods:
union,intersection,difference,symmetricDifference,isSubsetOf,isSupersetOf,isDisjointFrom. - Count with
map.set(k, (map.get(k) ?? 0) + 1); group withMap.groupBy; ES2026 addsgetOrInsertandgetOrInsertComputed. - Convert with spread,
Object.fromEntriesandObject.entriesbefore using JSON.
Practice Questions
What does this print?
const s = new Set([1, 2, 2, "2"]);
s.add(1);
console.log(s.size, [...s]);
Answer
3 [ 1, 2, '2' ]. The duplicate 2 and the re-added 1 are ignored; the string "2" is a different value.
Write a function that returns the values two arrays have in common, without duplicates.
Answer
const common = (a, b) => [...new Set(a).intersection(new Set(b))];
Before ES2025, use filter instead:
[...new Set(a)].filter((x) => new Set(b).has(x))
What does this print?
const m = new Map();
m.set("1", "str").set(1, "num");
console.log(m.size, m.get(1), m.get("1"));
Answer
2 num str. Unlike object keys, map keys aren't converted to strings, so 1 and "1" are separate keys.
Group these words by first letter into a Map:
["apple", "avocado", "banana", "blueberry", "cherry"]
Answer
Map.groupBy(fruits, (f) => f[0]) gives the code below.
Map(3) {
'a' => [ 'apple', 'avocado' ], 'b' => [ 'banana', 'blueberry' ], 'c' => [ 'cherry' ]
}
Next: WeakMap, WeakSet, WeakRef and FinalizationRegistry: Memory-Friendly References in JavaScript

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.