One pass with a Set of ids already seen: skip an item whose id is in the set, otherwise add the id and keep the item. That's O(n) time, keeps the first copy, and preserves order. The follow-ups come from real feeds. Keep the set across pages, because items shift between pages as new ones arrive. For compound keys, build a string (JSON.stringify([type, id])), because a Set compares objects by identity and 'a:b' + ':c' collides with 'a' + ':b:c'. When a repeated id can be a newer version, switch to a Map that replaces by updatedAt, and cap its size for long sessions.
Dedupe a list of fetched items by ID using a Set of seen IDs.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
filter with a Set: has and add are O(1) on average, so the whole pass is O(n), against O(n²) for findIndex-based dedupes. Set uses SameValueZero, so 1 and '1' are different ids. Normalise ids first if an API mixes types.
// One pass, a Set of ids already seen: O(n). The first copy of each id is kept, in order.function dedupeById(items) {const seen = new Set();return items.filter((item) => {if (seen.has(item.id)) return false;seen.add(item.id);return true;});}
passes 3 checks run on every build, against the native method where there is one
- keeps the first of each id, in order
- 1 and '1' are different ids (Set uses SameValueZero)
- linear: 200,000 items
With offset pagination, new items arriving at the top push older ones onto the next page, so page 2 repeats the end of page 1. Keeping the Set alive between fetches fixes that, and add returns only the new items to append. When uniqueness spans fields (type and id), make a string key. Objects in a Set are compared by identity, and joining with : can collide, so JSON.stringify the parts.
// Pages arrive one by one (infinite scroll, polling). Keep the Set between pages so an item// that shifts onto the next page isn't shown twice. Keys can combine fields: a Set compares// objects by identity, so build a string, with JSON so ('a:b', 'c') and ('a', 'b:c') differ.function createFeed(keyOf = (item) => item.id) {const seen = new Set();const items = [];return {add(page) {const fresh = [];for (const item of page) {const key = keyOf(item);if (seen.has(key)) continue;seen.add(key);fresh.push(item);}items.push(...fresh);return fresh; // what to append to the screen},get items() {return items;},};}const compoundKey = (...parts) => JSON.stringify(parts);
passes 4 checks run on every build, against the native method where there is one
- an item that moves to the next page isn't added twice
- compound keys: type and id together
- why not ':'-joined keys: they can collide
- why not objects as keys: a Set compares them by identity
In live feeds the same id comes back after an edit. A Map from id to item keeps first-seen order, and setting an existing key replaces the value without moving it, so an edited post updates in place. Compare updatedAt so stale copies from a slow request can't win. A long session would grow forever, so drop the oldest entries past maxItems (a Map iterates oldest first).
// Long-running feeds: a repeated id may be a newer version (an edited post), and memory can't// grow forever. A Map keeps one entry per id in first-seen order; a newer updatedAt replaces// the item in place; past maxItems the oldest entries are dropped.function createLiveFeed({ maxItems = Infinity } = {}) {const byId = new Map();return {upsert(page) {for (const item of page) {const current = byId.get(item.id);if (!current) byId.set(item.id, item);else if (item.updatedAt > current.updatedAt) byId.set(item.id, item); // set on an existing key keeps its position}while (byId.size > maxItems) byId.delete(byId.keys().next().value); // oldest first},get items() {return [...byId.values()];},};}
passes 3 checks run on every build, against the native method where there is one
- a newer version replaces the old one in place
- an older or equal version doesn't overwrite
- maxItems keeps memory bounded, dropping the oldest
Offset pagination repeats items
When rows are inserted while a user pages through, offset-based pages overlap. Cursor-based pagination avoids it, and client-side dedupe hides it.
React keys
Duplicate items with the same key make React warn and can reuse the wrong component state, so feeds dedupe before rendering.
Normalised caches
Client caches like Apollo's store each entity once by type and id, so every list showing it updates together, the Map idea from the advanced stage.
items.filter((x, i) => items.findIndex((y) => y.id === x.id) === i): correct but O(n²).Putting whole objects in the Set: two fetches return different objects with the same id.
Resetting the Set on every page fetch.
Joining compound keys with a separator that can appear in the values.
Letting a stale response overwrite a newer version.
Why does new Set(items) not dedupe fetched items?
Each fetch creates new objects, and a Set compares objects by reference, so equal-looking items are all different.
How would you keep the latest copy instead of the first?
Use a Map from id to item and always set, which keeps the first position with the last value, or iterate from the end and reverse.
How do you avoid duplicates at the source?
Cursor pagination ("items after id X") instead of offsets, so inserted items don't shift pages.