Skip to content
jshacks.dev
Fundamentals

Sets and Maps vs Objects and Arrays and When to Use Each

Use a Map for arbitrary keys, a Set for unique values, an object for fixed shapes and JSON, and an array for ordered lists. See the traps and set methods.

8 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.

JavaScript had one collection for most of its life, the object, and everything was forced into it: dictionaries, sets, counters, caches. ES2015 added Map and Set because objects are a poor dictionary. Their keys are strings, they inherit names like toString, and they reorder numeric keys. The choice is no longer between a hack and a built-in, but between four structures that each fit a different job, and the mistakes people make are using an object where a Map was needed or a Map where JSON was. This post compares the four on the properties that decide, with runnable output on Node.js 24, and finishes with the set operations that arrived in ES2025. The object rules are in the post on objects, and the array methods used in the examples are in the guide to modern JavaScript.

PropertyObjectMapSetArray
HoldsKey and valueKey and valueValues onlyValues by position
Key typesString and symbolAny valueNot applicableInteger index
DuplicatesKeys are uniqueKeys are uniqueValues are uniqueAllowed
OrderInteger keys, then insertionInsertionInsertionBy index
SizeObject.keys(o).lengthmap.sizeset.sizearr.length
Inherited namesYes, unless Object.create(null)NoNoMethods only
Serializes to JSONYesNo, becomes {}No, becomes {}Yes

Keys that are not strings

An object turns every key into a string. A Map keeps the key as it is, so objects, numbers and NaN work as keys.

JavaScript
const element = { id: "a" };
const asObject = {};
asObject[element] = "first";
asObject[1] = "number key";
asObject["1"] = "string key";

const asMap = new Map();
asMap.set(element, "first");
asMap.set(1, "number key");
asMap.set("1", "string key");
asMap.set(NaN, "nan key");

console.log(Object.keys(asObject));
console.log(asObject[{ other: true }]);
console.log(asMap.size, asMap.get(1), asMap.get("1"), asMap.get(NaN));
console.log(asMap.get({ id: "a" }), asMap.get(element));
Text
[ '1', '[object Object]' ]
first
4 number key string key nan key
undefined first

The object stored the element under the string "[object Object]", so any other object finds the same slot, and the number 1 and the string "1" collided. The Map kept all four entries apart. Object keys match by identity, as in the post on equality for objects, so a look-alike object does not find the entry. NaN works as a key because Map uses SameValueZero.

Dictionaries with arbitrary keys

When keys come from outside, such as words in a text or ids from a request, an object has two traps: inherited names and the special __proto__ key. A Map has neither.

JavaScript
const words = ["map", "constructor", "map", "__proto__", "toString"];

const objectCounts = {};
for (const word of words) {
  objectCounts[word] = (objectCounts[word] ?? 0) + 1;
}

const mapCounts = new Map();
for (const word of words) {
  mapCounts.set(word, (mapCounts.get(word) ?? 0) + 1);
}

console.log(objectCounts);
console.log([...mapCounts]);
console.log(mapCounts.size, mapCounts.has("toString"), "toString" in {});
Text
{
  map: 2,
  constructor: 'function Object() { [native code] }1',
  toString: 'function toString() { [native code] }1'
}
[
  [ 'map', 2 ],
  [ 'constructor', 1 ],
  [ '__proto__', 1 ],
  [ 'toString', 1 ]
]
4 true true

The object counter broke on the inherited names: constructor and toString produced strings and __proto__ was silently ignored. The Map counted all four distinct words correctly. A Map is the safe dictionary, and Object.create(null) is the object-shaped alternative when you must have property syntax.

Uniqueness and membership with Set

A Set stores each value once and checks membership without scanning. An array of the same data needs includes() or a filter.

JavaScript
const ids = [3, 1, 3, 2, 1, 3];

const unique = [...new Set(ids)];
console.log(unique);

const seen = new Set();
const duplicates = ids.filter((id) => (seen.has(id) ? true : (seen.add(id), false)));
console.log(duplicates);

const allowed = new Set(["read", "write"]);
console.log(allowed.has("write"), allowed.has("delete"));
console.log(allowed.size);

allowed.add("read");
allowed.delete("write");
console.log([...allowed]);
Text
[ 3, 1, 2 ]
[ 3, 1, 3 ]
true false
2
[ 'read' ]

Spreading a set into an array is the shortest way to deduplicate, and it keeps the first occurrence in order. has() is a lookup and add() of an existing value does nothing. For a short list, includes() is equally readable, and the Set pays off when the collection is large or queried repeatedly, as discussed in the includes() post.

Set operations

Since ES2025, sets have methods for the standard operations, available in Node.js 22 and later.

JavaScript
const frontend = new Set(["js", "css", "html"]);
const backend = new Set(["js", "sql", "node"]);

console.log(frontend.union(backend));
console.log(frontend.intersection(backend));
console.log(frontend.difference(backend));
console.log(frontend.symmetricDifference(backend));
console.log(new Set(["js"]).isSubsetOf(frontend));
console.log(frontend.isDisjointFrom(new Set(["sql"])));
Text
Set(5) { 'js', 'css', 'html', 'sql', 'node' }
Set(1) { 'js' }
Set(2) { 'css', 'html' }
Set(4) { 'css', 'html', 'sql', 'node' }
true
true

Each operation returns a new set and leaves the inputs alone, and the three predicates return booleans. They replace loops that filter one array against another, and they read as the question being asked. The post on what changed in ES2025 lists them with the iterator helpers.

Grouping with Map

Map.groupBy(), available since Node.js 21, groups items by a computed key and keeps non-string keys intact. Object.groupBy() does the same into an object with string keys.

JavaScript
const orders = [
  { id: 1, total: 40, status: "paid" },
  { id: 2, total: 15, status: "open" },
  { id: 3, total: 90, status: "paid" },
];

const byStatus = Map.groupBy(orders, (order) => order.status);
const byBand = Map.groupBy(orders, (order) => (order.total >= 50 ? "large" : "small"));

console.log([...byStatus.keys()]);
console.log(byStatus.get("paid").map((order) => order.id));
console.log([...byBand].map(([band, list]) => [band, list.length]));
console.log(Object.groupBy(orders, (order) => order.status).open);
Text
[ 'paid', 'open' ]
[ 1, 3 ]
[ [ 'small', 2 ], [ 'large', 1 ] ]
[ { id: 2, total: 15, status: 'open' } ]

Both produce one list per key in the order the keys first appeared. The Map result suits keys that are not strings, such as dates or objects, and the object result suits JSON and property access.

Size, order and iteration

A Map and a Set iterate in insertion order and expose size, and the iteration protocol makes them work with for...of, spread and destructuring. An object needs Object.keys() for the same, and integer-like keys come out first.

JavaScript
const object = { b: 1, 2: "two", a: 1, 1: "one" };
const map = new Map([["b", 1], [2, "two"], ["a", 1], [1, "one"]]);

console.log(Object.keys(object));
console.log([...map.keys()]);

for (const [key, value] of map) {
  if (key === "a") console.log("found", value);
}

map.forEach((value, key) => {
  if (key === 2) console.log("forEach", value);
});

console.log(Object.keys(object).length, map.size);
Text
[ '1', '2', 'b', 'a' ]
[ 'b', 2, 'a', 1 ]
found 1
forEach two
4 4

The object reordered its integer keys and the map did not. Order matters for anything shown to users or serialized, and a Map is the way to keep exactly the order entries were added.

Crossing the JSON boundary

JSON knows objects and arrays. A Map or Set serializes to {}, so convert at the edges.

JavaScript
const settings = new Map([["theme", "dark"], ["retries", 3]]);
const tags = new Set(["a", "b"]);

console.log(JSON.stringify({ settings, tags }));
console.log(JSON.stringify({ settings: Object.fromEntries(settings), tags: [...tags] }));

const restored = new Map(Object.entries(JSON.parse('{"theme":"dark","retries":3}')));
console.log(restored.get("retries"), restored instanceof Map);
Text
{"settings":{},"tags":{}}
{"settings":{"theme":"dark","retries":3},"tags":["a","b"]}
3 true

The direct serialization lost the contents. Object.fromEntries() and spread produced JSON-safe values, and new Map(Object.entries(...)) rebuilt the map on the way back. Maps with non-string keys cannot round-trip through a plain object, so use an array of pairs, [...map], for those.

A worked example: a small LRU cache

Insertion order is a feature you can build on. A least-recently-used cache needs to find the oldest entry quickly, and a Map gives it for free, because the first key in iteration order is the oldest one inserted. Deleting and re-inserting a key on every read moves it to the end.

JavaScript
class LruCache {
  #entries = new Map();

  constructor(limit) {
    this.limit = limit;
  }

  get(key) {
    if (!this.#entries.has(key)) return undefined;
    const value = this.#entries.get(key);
    this.#entries.delete(key);
    this.#entries.set(key, value);
    return value;
  }

  set(key, value) {
    this.#entries.delete(key);
    this.#entries.set(key, value);
    if (this.#entries.size > this.limit) {
      const oldest = this.#entries.keys().next().value;
      this.#entries.delete(oldest);
    }
  }

  keys() {
    return [...this.#entries.keys()];
  }
}

const cache = new LruCache(3);
cache.set("a", 1);
cache.set("b", 2);
cache.set("c", 3);
cache.get("a");
cache.set("d", 4);

console.log(cache.keys());
console.log(cache.get("b"), cache.get("a"));
Text
[ 'c', 'a', 'd' ]
undefined 1

Reading a made it the newest, so when d arrived and the limit was exceeded, b was the oldest and was evicted. The whole cache is about twenty lines, and it works because a Map keeps insertion order and allows deletion in any position. An object could not do this reliably, since integer-like keys reorder themselves. The pattern is a good test of whether a structure fits: if you need to remove the oldest, or the first, or the Nth key in order, you want a Map.

A choice you can apply

Pick an object for a record with known fields, for anything that must be JSON, and for configuration. Pick a Map for a dictionary whose keys are data, for non-string keys, for frequent insertion and deletion and for ordered key-value storage. Pick a Set for uniqueness and membership. Pick an array for ordered data, duplicates, indexing and the array methods. If you find yourself writing Object.keys(obj).length, delete obj[key] or key in obj on a dictionary, it wanted to be a Map.

Converting between them

Moving data between the structures is routine, and the conversions are worth knowing by heart. An array to a set and back deduplicates. A map to an array of pairs, [...map], and back, new Map(pairs), is the lossless route for any keys. An object to a map goes through Object.entries(), and a map to an object through Object.fromEntries(), which drops non-string keys by turning them into strings. A set of values into a Map takes one map call to build pairs. Each conversion copies, so do them at boundaries and keep one structure inside a module.

Where this advice stops

For small collections, readability beats any structural choice: a three-field object is better as an object, and a ten-item list is fine as an array with includes(). Performance claims for these structures depend on the engine and the data, and we would not pick one for speed without a measurement on your workload. And in TypeScript, a Record<string, T> is typed like an object, while Map<K, V> keeps the key type, which is a real advantage for non-string keys.

The collections are defined in the specification under keyed collections, and MDN's pages on Map and Set list every method.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.