Which structure fits the job?
| Structure | Choose for | Example |
|---|---|---|
| Array | Ordered list | Search results |
| Object | Named record fields | Product configuration |
| Map | Keyed lookup | Product index by ID |
| Set | Membership and uniqueness | Selected IDs |
const product = { id: "p1", name: "Keyboard", price: 49 };
const products = [
product,
{ id: "p2", name: "Mouse", price: 29 },
];
const productsById = new Map(products.map((item) => [item.id, item]));
const selectedIds = new Set(["p2"]);
const selectedProducts = products.filter((item) => selectedIds.has(item.id));
console.log(productsById.get("p1")?.name); // "Keyboard"
console.log(selectedProducts.map((item) => item.id)); // ["p2"]
Array models a sequence with indexed access, filtering and sorting. Object represents named fields such as a product or configuration. Map associates keys with values; Set stores unique values. [1]
A catalog can remain an array, its lookup index a map and selected identifiers a set. Filtering preserves source array order in the example, and the map returns the original product reference rather than a clone.
How can repeated find() calls be avoided?
function indexProducts(products) {
const productsById = new Map();
for (const product of products) {
if (productsById.has(product.id)) {
throw new Error(`Duplicate product ID: ${product.id}`);
}
productsById.set(product.id, product);
}
return productsById;
}
const products = [{ id: "p1", stock: 0 }, { id: "p2", stock: 5 }];
const productsById = indexProducts(products);
console.log(productsById.has("p1")); // true
console.log(productsById.get("p1")?.stock); // 0
console.log(productsById.has("p3")); // false
Each find() can scan the entire array in the worst case. Build a Map index once and reuse get() and has(). Setting an existing key replaces its value. [2][3]
Duplicate product identifiers may indicate corrupt input, so the example rejects them explicitly. has() distinguishes an absent entry from one holding undefined; testing truthiness would also misclassify valid zero stock. Rebuild or update the index when identifiers change.
Why are Object and Map not interchangeable?
const settings = new Map([
[1, "numeric key"],
["1", "string key"],
["theme", undefined],
]);
const labels = Object.create(null);
labels["__proto__"] = "literal label";
console.log(settings.size); // 3
console.log(settings.has("theme")); // true
console.log(settings.get("missing")); // undefined
console.log(Object.hasOwn(labels, "__proto__")); // true
console.log(Object.keys({ 10: "a", 2: "b", name: "c" }));
// ["2", "10", "name"]
Object property keys are strings or symbols; numeric 1 becomes a string key. Map distinguishes 1 from "1" and compares object keys by identity. Updating an existing Map entry does not move its insertion position. Object array-index keys are enumerated numerically before other string keys. [2][4]
User-controlled dictionary keys must not accidentally read inherited properties. Map or Object.create(null) avoids that issue; Object.hasOwn() tests ownership rather than inheritance. Still validate data and avoid uncontrolled copying of keys into ordinary objects. [5][6]
How do you deduplicate records by ID?
function uniqueById(items) {
const seenIds = new Set();
const uniqueItems = [];
for (const item of items) {
if (seenIds.has(item.id)) {
continue;
}
seenIds.add(item.id);
uniqueItems.push(item);
}
return uniqueItems;
}
const records = [
{ id: "a", label: "First" },
{ id: "a", label: "Second" },
{ id: "b", label: "Third" },
];
console.log(new Set(records).size); // 3
console.log(uniqueById(records).map((item) => item.label));
// ["First", "Third"]
const available = new Set(["a", "b"]);
const requested = new Set(["b", "c"]);
const matching = [...requested].filter((id) => available.has(id));
console.log(matching); // ["b"]
Set uses SameValueZero: NaN equals itself and +0 and -0 are equivalent. Separate objects with identical fields are distinct. Track identifiers to deduplicate records by business identity. [4][7]
The function keeps the first record and its position. If the newest record should win, define a replacement rule explicitly. Set intersection can be computed with filter() and has() or the native intersection() where supported. Membership in the client does not replace server authorization. [7]
How can records be grouped by category?
function groupByCategory(products) {
const groups = new Map();
for (const product of products) {
const group = groups.get(product.category);
if (group) {
group.push(product);
} else {
groups.set(product.category, [product]);
}
}
return groups;
}
const products = [
{ id: "p1", category: "audio" },
{ id: "p2", category: "office" },
{ id: "p3", category: "audio" },
];
const groups = groupByCategory(products);
console.log(groups.get("audio")?.map((product) => product.id));
// ["p1", "p3"]
Map can group records using keys beyond strings. Each category in the example has a separate array; push() changes only a locally created collection, not the input array.
Where supported, Map.groupBy(products, (product) => product.category) is a concise alternative. Object.groupBy() returns a null-prototype object and groups by string or symbol keys. Both preserve references to original records. Check runtime support; the manual implementation is an alternative. [8][9]
How do Map and Set survive JSON serialization?
function restoreStock(json) {
const entries = JSON.parse(json);
if (!Array.isArray(entries)) {
throw new TypeError("Expected an array of entries");
}
const stock = new Map();
for (const entry of entries) {
if (
!Array.isArray(entry) ||
entry.length !== 2 ||
typeof entry[0] !== "string" ||
!Number.isSafeInteger(entry[1]) ||
entry[1] < 0
) {
throw new TypeError("Invalid stock entry");
}
const [id, quantity] = entry;
if (stock.has(id)) {
throw new TypeError(`Duplicate stock ID: ${id}`);
}
stock.set(id, quantity);
}
return stock;
}
const stock = new Map([
["p1", 0],
["p2", 4],
]);
const json = JSON.stringify([...stock]);
const restoredStock = restoreStock(json);
console.log(restoredStock.get("p1")); // 0
console.log(JSON.stringify(stock)); // "{}"
Default JSON serialization produces {} for ordinary Map and Set instances because entries are not enumerable own properties. Define an array-of-pairs contract for string-keyed numeric maps, and an array-of-values contract for sets of IDs. [10]
The decoder checks each pair, key type, nonnegative safe integer quantity and duplicate ID. This is not a universal format: JSON cannot preserve object-key identity, undefined or symbols. Untrusted input also needs application-specific size limits.
How should Set be updated in React state?
function toggleSelection(previousSelection, id) {
const nextSelection = new Set(previousSelection);
if (nextSelection.has(id)) {
nextSelection.delete(id);
} else {
nextSelection.add(id);
}
return nextSelection;
}
const previousSelection = new Set(["p1"]);
const nextSelection = toggleSelection(previousSelection, "p2");
console.log([...previousSelection]); // ["p1"]
console.log([...nextSelection]); // ["p1", "p2"]
add(), delete() and set() mutate their existing collections. Mutating React state breaks the snapshot model and may hide updates. The helper creates a fresh Set, changes only the copy and returns a new reference. [11]
Call setSelectedIds((previous) => toggleSelection(previous, id)) in a component. Copying a set is shallow and costs work proportional to its size. Object-valued entries remain shared. Consider arrays or an explicit interchange format for serialized state.
Are Map and Set always faster?
const products = Array.from({ length: 10_000 }, (_, index) => ({
id: `p${index}`,
price: index,
}));
const requestedIds = ["p9999", "missing", "p9998"];
let comparisons = 0;
const scanned = requestedIds.map((id) =>
products.find((product) => {
comparisons += 1;
return product.id === id;
}),
);
const productsById = new Map(
products.map((product) => [product.id, product]),
);
const indexed = requestedIds.map((id) => productsById.get(id));
console.log(comparisons); // 29999
console.log(indexed.every((product, index) => product === scanned[index]));
// true
The specification requires average access time that grows slower than linearly with collection size, not guaranteed O(1) for every operation. find() and includes() can examine every element; building a map or set also traverses data and consumes additional memory. [3][7]
The example counts 29,999 predicate calls for three searches over 10,000 records. The index is built from 10,000 entries and then serves three get() calls. These are source-level operation counts, not elapsed-time or memory benchmarks. A small array may be better for a one-off search. Measure construction, reads, updates and index maintenance separately.
