Sub topic 11
Choosing a Search Strategy: Complexity, Set, and Map
The earlier chapters covered the built-in search methods (indexOf, includes, find and their relatives) and binary search on a sorted array. This chapter is about choosing between them. On a ten-element array the choice barely matters. On a hundred thousand elements searched thousands of times, the wrong choice can turn milliseconds into seconds. Here you will learn to estimate the cost of each strategy, when to build a Set or Map index instead of scanning, and when a sorted array is still the better tool.
This chapter assumes you know:
- The search methods from the previous chapters, and the binary search function shown there.
- Basic Big-O notation: O(n) means the work grows in proportion to the input size n, O(log n) grows very slowly, and O(1) stays roughly constant.
- How to create objects and arrays and use arrow functions.
The Cost of Each Strategy
Every search strategy has two possible costs: a one-time setup cost and a cost per lookup. Linear methods have no setup cost but are slow per lookup. Indexes have a setup cost and are fast per lookup.
| Strategy | Setup cost | Cost per lookup | Supports |
|---|---|---|---|
| `includes`, `indexOf`, `find` | none | O(n) | any value or condition |
| Binary search | O(n log n) to sort, once | O(log n) | exact match, ranges, nearest value |
| `Set` | O(n) to build | about O(1) on average | exact membership only |
| `Map` | O(n) to build | about O(1) on average | exact key to value |
A linear scan is O(n) because in the worst case it checks every element, for example when the target is missing. Binary search halves the range at each step, so 1,000,000 sorted elements need at most about 20 comparisons. Set and Map use hashing or a similar structure, so a lookup goes almost directly to the right slot.
One Lookup Versus Many
Setup cost is the deciding factor. For a single lookup, building a Set means walking the whole array once to insert every element, which is already as much work as one includes call. Indexing only pays off when you search the same data repeatedly.
With n elements and k lookups:
- Linear scanning costs about k × n.
- Building a
Setand then querying costs about n + k.
With n = 100,000 and k = 10,000, that is roughly 1,000,000,000 steps against 110,000. The most common place this hides is a lookup inside a loop or callback, such as computing the intersection of two arrays:
function intersectSlow(a, b) {
// b.includes scans b for every element of a: O(a.length * b.length)
return a.filter(x => b.includes(x));
}
function intersectFast(a, b) {
// Build the Set once, then each check is near-constant: O(a.length + b.length)
const bSet = new Set(b);
return a.filter(x => bSet.has(x));
}
const left = [1, 4, 7, 9, 12];
const right = [9, 2, 4, 15];
console.log(intersectSlow(left, right)); // [4, 9]
console.log(intersectFast(left, right)); // [4, 9]Both functions return the same result. The fast version builds the Set outside the filter callback, which is the important detail. If you wrote a.filter(x => new Set(b).has(x)), you would rebuild the set for every element and end up slower than the original.
Set for Membership Checks
Use a Set when your question is "is this value present?" It also removes duplicates as a side effect.
const tags = ['js', 'css', 'js', 'html', 'css'];
const uniqueTags = new Set(tags);
console.log(uniqueTags.size); // 3
console.log(uniqueTags.has('css')); // true
console.log([...uniqueTags]); // ['js', 'css', 'html']A Set keeps insertion order, so spreading it back into an array gives you the first occurrence of each value in its original order.
How Set Decides Two Values Are Equal
Set and Map compare values with SameValueZero, the same algorithm includes uses. This affects edge cases in three ways:
const s = new Set([NaN, 0, { id: 1 }]);
console.log(s.has(NaN)); // true: NaN matches NaN
console.log(s.has(-0)); // true: -0 and +0 are treated as equal
console.log(s.has({ id: 1 })); // false: a different object with the same contentsThe third result causes the most bugs. Objects are compared by reference, so a Set of objects only finds the exact same object instance. Two objects that look identical are different keys.
Composite Keys
If you need to check membership by content, for example "have I already seen this (x, y) point?", turn the content into a primitive key, usually a string:
const points = [
{ x: 1, y: 2 },
{ x: 3, y: 4 },
{ x: 1, y: 2 }
];
const seen = new Set();
const uniquePoints = [];
for (const p of points) {
const key = `${p.x}|${p.y}`;
if (!seen.has(key)) {
seen.add(key);
uniquePoints.push(p);
}
}
console.log(uniquePoints.length); // 2Pick a separator that cannot appear in the values. With free-text fields, 'a|b' + '|' + 'c' and 'a' + '|' + 'b|c' produce the same key. JSON.stringify([p.x, p.y]) avoids that collision at a small extra cost.
Map for Lookup by Key
Use a Map when you search for a record by some field and need the record back, not just a yes or no. The usual pattern is "find by id" replaced with an index built once:
const orders = [
{ id: 1, status: 'paid', total: 40 },
{ id: 2, status: 'pending', total: 15 },
{ id: 3, status: 'paid', total: 90 }
];
// Linear: scans on every call
console.log(orders.find(o => o.id === 3).total); // 90
// Indexed: build once, then near-constant lookups
const byId = new Map(orders.map(o => [o.id, o]));
console.log(byId.get(3).total); // 90
console.log(byId.get(99)); // undefined
console.log(byId.has(99)); // falseThe Map holds references to the same objects as the array, not copies, so the extra memory is the index structure itself. A change to orders[2].total shows up through byId.get(3) as well.
If the key is not unique, map each key to an array of matches. This replaces repeated filter calls:
const byStatus = new Map();
for (const o of orders) {
const list = byStatus.get(o.status);
if (list) list.push(o);
else byStatus.set(o.status, [o]);
}
console.log(byStatus.get('paid').map(o => o.id)); // [1, 3]
console.log(byStatus.get('refunded')); // undefinedIn environments that support ES2024, Map.groupBy(orders, o => o.status) builds the same structure in one call.
Why Not a Plain Object?
Plain objects can serve as lookup tables, but they have two gotchas that Map avoids:
- Keys are converted to strings, so
1and'1'collide, and an object key becomes'[object Object]'. - Inherited properties look like entries.
'constructor' in {}istrue, so a user-supplied key like"constructor"or"__proto__"can give wrong answers or cause security problems.
If you do use an object, create it with Object.create(null) and check keys with Object.hasOwn. For dynamic keys, Map is the safer default.
When a Sorted Array Wins
A Set or Map only answers exact-match questions. It cannot tell you "all prices between 8 and 15", "the first event after 14:00", or "the closest value to 42". A sorted array with binary search answers all of these in O(log n).
For range queries, the standard tools are two variants of binary search. lowerBound returns the first index whose value is greater than or equal to the target, and upperBound returns the first index whose value is strictly greater:
function lowerBound(sorted, target) {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (sorted[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
function upperBound(sorted, target) {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (sorted[mid] <= target) lo = mid + 1;
else hi = mid;
}
return lo;
}
const prices = [3, 8, 8, 12, 15, 21, 30];
const from = lowerBound(prices, 8); // 1
const to = upperBound(prices, 15); // 5
console.log(prices.slice(from, to)); // [8, 8, 12, 15]
console.log(to - from); // 4 prices in the rangeUnlike the exact-match binary search, these functions never return -1. They return an insertion point, which also tells you where a new value belongs to keep the array sorted. Duplicates are handled correctly: both 8s are included.
The precondition from the binary search chapter still applies. The array must be sorted in the same order the comparison assumes, here ascending numeric order from (a, b) => a - b. If you run it on an array sorted with the default string sort, it silently returns wrong answers.
Keeping Indexes in Sync
An index is a second copy of information about your data, and it goes stale when the data changes. Each strategy reacts to changes differently:
| Change to the data | Linear scan | Sorted array | Set / Map index |
|---|---|---|---|
| Append an item | nothing to do | insert at `lowerBound` position, O(n) shift | `add` or `set`, near O(1) |
| Remove an item | nothing to do | `splice`, O(n) | `delete`, near O(1) |
| Change a key field | nothing to do | remove and reinsert | delete old key, set new key |
| Bulk replace | nothing to do | re-sort, O(n log n) | rebuild, O(n) |
Linear scans can never be stale, which is a real advantage. If your data changes constantly and you search it rarely, an index adds bugs and costs more than it saves. A common pattern is to wrap the array and its index in one module or class, so that every change goes through functions that update both.
Measuring Instead of Guessing
Big-O describes how cost grows, not the actual time on small inputs. For a few dozen elements, includes is often as fast as Set.has or faster, because a tight scan over a small contiguous array is cheap for the CPU. Measure when it matters:
const data = Array.from({ length: 100_000 }, (_, i) => i * 2);
const queries = Array.from({ length: 10_000 }, (_, i) => i * 7);
function time(label, fn) {
const start = performance.now();
const result = fn();
const ms = (performance.now() - start).toFixed(1);
console.log(`${label}: ${ms} ms, hits = ${result}`);
}
time('includes', () => queries.filter(q => data.includes(q)).length);
time('Set build + has', () => {
const set = new Set(data);
return queries.filter(q => set.has(q)).length;
});Both lines report hits = 5000. On typical hardware the includes version takes hundreds of milliseconds and the Set version takes a few milliseconds, even though the Set timing includes building it. The exact numbers depend on your engine and machine, so run the code yourself. Try length: 50 for data to see the gap shrink or reverse.
A Decision Guide
The questions below cover most real cases. Start with what you are asking of the data, then consider how often you ask.
Condition-based searches like "first order over 100 with status pending" have no general index, so a linear predicate search is the default. If one condition is queried constantly, you can sometimes index the field it tests, for example with a Map from status to orders, and then scan only the smaller group.
Common Mistakes
- Building the index inside the loop.
new Set(arr)ornew Map(...)inside a callback rebuilds it each time and makes things worse. - Using objects as Set members and expecting content equality. Use a primitive key such as an id or an encoded string.
- Binary searching an array that was sorted differently. The comparator for sorting and for searching must agree.
- Forgetting the index after mutation. Pushing to the array without updating the
Mapreturnsundefinedfor new items. - Optimizing tiny arrays. An index on a 10-element list adds code and memory for no measurable gain.
Exercise
A function receives an array of 50,000 user objects with unique email fields, then is called 20,000 times with an email to return the matching user. The current code uses users.find(u => u.email === email). Rewrite the approach and estimate the old and new costs in Big-O terms.
Show answer
Build const byEmail = new Map(users.map(u => [u.email, u])) once, then answer each call with byEmail.get(email). The old approach costs about O(k × n) = 20,000 × 50,000 = 10^9 comparisons in the worst case. The new one costs O(n + k), about 70,000 operations plus hashing. Rebuild or update the Map if users are added, removed, or change email.
Exercise
You store event timestamps (numbers, in milliseconds) and frequently need all events between two times. Would a Set, a Map, or a sorted array be the better structure, and why?
Show answer
A sorted array. Set and Map only support exact-key lookups, so a range query would still need a full scan. With the timestamps sorted ascending using (a, b) => a - b, lowerBound(times, start) and upperBound(times, end) find the range boundaries in O(log n), and slice between them returns the matches.
Exercise
This code prints false. Explain why and fix it so it prints true.
const visited = new Set();
visited.add({ row: 2, col: 3 });
console.log(visited.has({ row: 2, col: 3 }));
Show answer
Set compares objects by reference using SameValueZero, and the two object literals are different objects even though their contents match. Use a primitive key instead: visited.add('2,3') and visited.has('2,3'), or in general build the key with ${row},${col}.