In this article
Two API records can have the same ID and still be different JavaScript objects. A Set keeps both. Before accepting a generated deduplication helper, decide what counts as the same record and which version should survive.
Two objects, one record, three visible rows
An API response contains a task twice: once near the start and once in an overlapping page. You ask a coding assistant to remove duplicates, and it proposes spreading new Set(rows). The expression is short, familiar, and wrong for this request. The two task objects were created separately. Sharing an ID does not make them the same object.
Here is an illustrative fixture, rather than a report of an nrml incident. Task t7 appears as both Draft and Published. Task t2 appears between those versions. The duplicate has different content on purpose: if both copies were identical, a test might confirm the row count while missing which version survived. Run this block with Node, then append the later blocks to the same file.
import assert from 'node:assert/strict';
const first = Object.freeze({ id: 't7', title: 'Draft' });
const other = Object.freeze({ id: 't2', title: 'Review' });
const later = Object.freeze({ id: 't7', title: 'Published' });
const rows = Object.freeze([first, other, later]);
const byReference = [...new Set(rows)];
assert.equal(byReference.length, 3);
assert.deepEqual(byReference.map(row => row.id), ['t7', 't2', 't7']);
Decide what a duplicate means before choosing a collection
For this exercise, IDs are validated nonempty strings. Keep the first object for each ID, keep the order in which those IDs first appear, and leave the input untouched. These choices describe a display helper that trusts the earlier record. They are requirements for this example, not a universal policy for merging API responses. If later data is authoritative, the survivor rule must change.
MDN documents that Set compares objects by reference. Repeating first twice would therefore collapse to one entry, while a separately allocated object with the same fields remains distinct. That explains why a demonstration using [first, first] can pass even though the actual API case fails. Use separate object instances when evaluating a proposed repair. MDN: Set value equality
Also distinguish deduplication from reconciliation. This helper chooses one existing record; it does not merge titles, compare revision numbers, or resolve concurrent edits. A name such as firstById makes that limited job visible to callers. A vague name such as cleanRecords makes it easier for the next change to quietly add a different rule.
Keep the first value for each explicit key
A Map makes the key choice explicit. Store a row only when its ID has not appeared. The membership check is the part that implements first-wins behavior; merely changing Set to Map does not establish that policy. MDN specifies both key insertion order and the fact that setting an existing key replaces its value. MDN: Map keys and insertion order
Returning the stored values gives the requested first-seen order without sorting. The returned array is new, but its entries are the original objects. That is deliberate: callers retain record identity. Freezing the fixture helps expose an accidental in-place edit during this exercise; the helper itself neither freezes data nor promises that returned objects cannot later change.
function firstById(input) {
const kept = new Map();
for (const row of input) {
if (!kept.has(row.id)) kept.set(row.id, row);
}
return [...kept.values()];
}
const result = firstById(rows);
assert.deepEqual(result.map(row => row.id), ['t7', 't2']);
assert.deepEqual(result.map(row => row.title), ['Draft', 'Review']);
assert.strictEqual(result[0], first);
assert.strictEqual(result[1], other);
assert.notStrictEqual(result, rows);
assert.deepEqual(rows, [first, other, later]);
The shorter Map expression changes which version wins
An assistant may offer new Map(input.map(row => [row.id, row])) as a cleanup. In this fixture it produces the right IDs in the right order, yet keeps Published instead of Draft. Updating the t7 entry replaces its value without moving that key behind t2. The output therefore combines the last value with the first insertion position. MDN: Map keys and insertion order
That behavior can be useful, but the original request did not authorize it. The assertion below rejects this alternative using the title chosen before inspecting either implementation. It also checks repeated references and an empty list. A second call with a different batch checks that the helper has not accidentally retained a module-level collection between invocations.
const lastById = input => [...new Map(
input.map(row => [row.id, row])
).values()];
assert.deepEqual(lastById(rows).map(row => row.id), ['t7', 't2']);
assert.throws(() => assert.deepEqual(
lastById(rows).map(row => row.title), ['Draft', 'Review']
), { code: 'ERR_ASSERTION' });
assert.deepEqual(firstById([first, first]), [first]);
assert.deepEqual(firstById([]), []);
assert.deepEqual(firstById([later]).map(row => row.title), ['Published']);
console.log('deduplication checks passed');
Give the assistant the conflict, not just the happy path
A useful review request includes the three-row fixture and the sentence: keep the first object per string ID in first-seen order, without modifying any input. Ask the assistant to identify the result of its proposal for both versions of t7. An explanation that says only unique objects remain has skipped the central question about record identity.
Read the final diff for changes to the input contract. Stringifying every ID, lowercasing it, or treating an absent ID as one shared key introduces new equivalences. Adding a deep clone changes reference identity. None of those changes follows from removing duplicate task IDs. Require a separate reason and a corresponding example before expanding the helper in those directions.
A display helper cannot establish which record is newest
First-wins is easy to explain and inspect, but it trusts input order. If overlapping responses can contain newer revisions, write down the revision comparison and what happens when revisions tie. Do not infer recency from where an object happens to sit in an array. This example intentionally contains no timestamp because a timestamp would invite a policy the helper has not implemented.
For a long-lived stream, a growing Map also retains one entry per distinct ID. Decide when that collection should be discarded or bounded before turning this batch helper into persistent state. For the array helper here, every call owns its collection. The cost of remembering IDs is part of the chosen approach; no benchmark or engine-independent constant-time guarantee is needed to justify this small repair.
Common questions about deduplicating records
Can I put the IDs in a Set instead? Yes, while building an output array from the first row for each unseen ID. A Set of primitive string IDs represents the intended equality; a Set of row objects does not. Choose whichever version makes the survivor policy easiest to read.
Should duplicates with conflicting titles throw an error? They should if conflict rejection is the product requirement. In that case the fixture should expect rejection rather than quietly choose Draft. Can I deduplicate by the whole serialized object? That answers a different question: two versions of t7 have different content and would still both remain. Decide the business identity first.
Sources & editorial notes
This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.
- MDN: Set value equality
Checked November 30, 2026. Reference documentation for Set equality, including separately allocated objects with equal fields.
- MDN: Map keys and insertion order
Checked November 30, 2026. Reference documentation for Map membership, value replacement, and original key insertion order.
Put the reading into practice
Work through an existing repository, review AI suggestions, and test the decisions behind your changes.
Explore practice problems