Deduplicate JavaScript Records by ID with Explicit Ordering
Two overlapping inventory pages contain the same item ID. Rendering their concatenated records produces duplicate rows, but removing duplicates also raises two decisions: which record supplies the fields, and where should that record appear?
Use an explicit ID and ordering policy before updating the interface. The examples below use ordinary data records with nonempty string IDs and run in modern browsers or Node.js 20 or later. They do not fetch data or modify the input records.
See Why Set Keeps Separate Objects
Two objects with equal fields remain different values:
For objects,
Set compares references
, rather than inspecting fields. Creating a set of records therefore does not express uniqueness by id.
Creating new Set(records.map(record => record.id)) produces unique IDs, but discards the associated records. A Map can associate each ID with the chosen record while retaining a defined traversal order.
Choose the Winner and the Position Separately
Consider the input IDs sword, shield, sword, where the second sword record has a different quantity. Define one of these policies:
| Policy | Record kept for sword | Output IDs |
|---|---|---|
first | First occurrence | sword, shield |
last | Last occurrence | sword, shield |
last-position | Last occurrence | shield, sword |
The last policy updates a row’s data while preserving its first appearance in the combined list. The last-position policy orders the surviving records by their final occurrence in the input. Neither policy sorts IDs or examines timestamps.
Map iteration follows initial key insertion order
. Replacing the value for an existing key leaves its position intact. Deleting the entry before inserting it again moves that key to the end. The
ECMAScript definition of Map.prototype.set
specifies updating an existing entry or appending a new one.
Implement the Policies with Map
Save this module as dedupe.mjs:
| |
The function validates even a duplicate that would be skipped. Malformed input throws instead of returning a partially processed list. It allocates a new result array and stores references to selected records; it does not merge fields or clone objects.
IDs are exact strings. The helper does not trim, lowercase, or coerce them: "01" and "1" remain distinct, and numeric 1 is rejected. Apply any required canonicalization at your data boundary. A whitespace-only string is accepted by this minimal contract; impose stricter ID rules if your application requires them.
Run this example beside the module:
| |
Unlike dynamic assignment into a normal object, Map treats "__proto__" and "constructor" as ordinary keys. It also preserves the arrival order of numeric-looking string IDs without object property enumeration rules intervening.
Test Selection, Ordering, and Invalid Records
Save this as test-dedupe.mjs and run node test-dedupe.mjs:
| |
The frozen fixtures check that all three policies work without rearranging the input or changing record fields. Reference equality verifies that selection returns the intended original object. The unusual IDs catch implementations that accidentally depend on object property ordering or inherited names.
Keep Identity Separate from Freshness
Here, last means later in this array. A slower response can contain older data, and concatenating it last does not make it authoritative. If your API provides revision numbers, define a separate comparison and conflict policy before choosing a winner. Do not infer freshness from request completion order.
The helper keeps one map entry per distinct ID, plus the returned array. It makes one traversal with a bounded number of map operations per record. Avoid claiming a universal worst-case constant lookup time: ECMAScript requires average access time to be sublinear, without mandating a particular map implementation.
Changing a selected object later also changes the record visible through the result, because both arrays reference that object. Keep records immutable in application state, or clone them according to the actual data model when independent copies are required. Deduplication establishes one row per ID under the chosen policy; schema validation, revision resolution, and ownership of mutable data remain separate decisions.