Sub topic 11
Choosing a Search Strategy: Complexity, Set, and Map
This chapter assumes you know the built-in search methods (indexOf, includes, find, filter) and the binary search function from the previous chapter. It also assumes you are comfortable with object property access and arrow functions. Here we look at what each search approach costs and when to switch to a different data structure.
The cost of each approach
Time complexity describes how the work grows as the array grows. O(n) means the work grows in step with the number of elements. O(log n) means it grows very slowly. O(1) means it stays about the same no matter how much data you have.
| Approach | Setup cost | Cost per lookup | Good for |
|---|---|---|---|
| `indexOf`, `includes`, `find`, `some` | None | O(n) | One-off or rare searches, small arrays |
| `filter` | None | O(n), always scans everything | Collecting every match |
| Binary search | O(n log n) to sort, unless already sorted | O(log n) | Sorted data, range and "nearest" queries |
| `Set.has` | O(n) to build | O(1) average | Repeated "is it in there?" checks |
| `Map.get` | O(n) to build | O(1) average | Repeated lookup of a record by key |
One linear scan is cheap. The cost only adds up when you repeat it. A single includes call on 10,000 items is fine. The same call inside a loop that runs 10,000 times does up to 100 million comparisons.
Hidden quadratic loops
The most common performance bug is a linear search inside another loop. Finding the items two arrays have in common is a typical case:
const a = Array.from({ length: 5000 }, (_, i) => i * 2);
const b = Array.from({ length: 5000 }, (_, i) => i * 3);
// O(n * m): includes rescans b for every element of a
const slow = a.filter(x => b.includes(x));
// O(n + m): build the Set once, then each check is O(1) on average
const bSet = new Set(b);
const fast = a.filter(x => bSet.has(x));
console.log(slow.length, fast.length); // 1667 1667Both versions produce the same result. The second does one pass over b to build the Set and one pass over a to check membership.
Map for lookups by key
When you keep looking up records by an ID with find, build a Map once and use it from then on:
const users = [
{ id: 101, name: 'Ana' },
{ id: 205, name: 'Bo' },
{ id: 317, name: 'Cy' }
];
const byId = new Map(users.map(u => [u.id, u]));
console.log(byId.get(205).name); // 'Bo'
console.log(byId.has(999)); // false
console.log(byId.get(999)); // undefinedThe Map holds references to the same objects as the array. A change made through one shows up in the other. Adding or removing elements in the array does not update the Map, though. You have to keep the two in sync yourself.
Common errors
Expecting Set to compare objects by content
Set and Map match keys with SameValueZero, the same rule includes uses. Objects match only when they are the same reference:
const seen = new Set([{ id: 1 }]);
console.log(seen.has({ id: 1 })); // false: a different object
const key = { id: 1 };
const seen2 = new Set([key]);
console.log(seen2.has(key)); // true: same referenceTo check objects by content, store a primitive key such as obj.id or a string you build from several fields.
Building the structure on every call
If you write new Set(arr).has(x) inside a loop, every iteration pays the O(n) build cost. That is slower than plain includes. Build the structure once, outside the loop.
Sorting just to search once
Sorting costs O(n log n). For a single lookup, a linear O(n) scan is cheaper. Binary search pays off when the data is already sorted, or when you need ordered queries that a Set cannot answer, such as "the first price at or above 50".
Choosing a strategy
Memory matters too. A Set or Map is a second structure stored next to your array. That extra memory is usually worth it for fast lookups, but on very large datasets that rarely change, a sorted array with binary search uses less of it.
Exercise
A function receives an array of 20,000 order objects and an array of 3,000 customer IDs flagged for review. It returns the orders whose customerId is flagged, using orders.filter(o => flagged.includes(o.customerId)). What is the cost, and how would you rewrite it?
Show answer
Each of the 20,000 orders triggers an O(m) scan of the 3,000 IDs, so the total is about 60 million comparisons, or O(n * m). Build const flaggedSet = new Set(flagged) once before filtering, then use orders.filter(o => flaggedSet.has(o.customerId)). That is O(n + m), about 23,000 operations. The IDs are primitives, so SameValueZero matching works correctly.
Exercise
Why does new Set([{ sku: 'A1' }]).has({ sku: 'A1' }) return false, and how do you fix the membership check?
Show answer
Set compares objects by reference, and the two object literals are different objects. Store a primitive key instead: new Set(items.map(i => i.sku)).has('A1') returns true.