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:

1
2
3
4
5
const first = { id: "sword", quantity: 1 };
const second = { id: "sword", quantity: 2 };

console.log(new Set([first, second]).size); // 2
console.log(new Set([first, first]).size);  // 1

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:

PolicyRecord kept for swordOutput IDs
firstFirst occurrencesword, shield
lastLast occurrencesword, shield
last-positionLast occurrenceshield, 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
export function dedupeById(records, policy = "first") {
  if (!Array.isArray(records)) {
    throw new TypeError("records must be an array");
  }
  if (!["first", "last", "last-position"].includes(policy)) {
    throw new TypeError("unknown duplicate policy");
  }

  const byId = new Map();
  for (const record of records) {
    if (record === null || typeof record !== "object" ||
        Array.isArray(record) || !Object.hasOwn(record, "id")) {
      throw new TypeError("each record must have its own string id");
    }
    const id = record.id;
    if (typeof id !== "string" || id.length === 0) {
      throw new TypeError("id must be a nonempty string");
    }

    if (policy === "first" && byId.has(id)) continue;
    if (policy === "last-position") byId.delete(id);
    byId.set(id, record);
  }
  return [...byId.values()];
}

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { dedupeById } from "./dedupe.mjs";

const records = [
  { id: "sword", quantity: 1 },
  { id: "shield", quantity: 3 },
  { id: "sword", quantity: 2 },
];

for (const policy of ["first", "last", "last-position"]) {
  const result = dedupeById(records, policy);
  console.log(policy, result.map(r => `${r.id}:${r.quantity}`).join(","));
}
// first sword:1,shield:3
// last sword:2,shield:3
// last-position shield:3,sword:2

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import assert from "node:assert/strict";
import { dedupeById } from "./dedupe.mjs";

const a1 = Object.freeze({ id: "a", quantity: 1 });
const b = Object.freeze({ id: "b", quantity: 2 });
const a2 = Object.freeze({ id: "a", quantity: 3 });
const c = Object.freeze({ id: "c", quantity: 4 });
const input = Object.freeze([a1, b, a2, c, b]);

assert.deepEqual(dedupeById(input), [a1, b, c]);
assert.deepEqual(dedupeById(input, "last"), [a2, b, c]);
assert.deepEqual(dedupeById(input, "last-position"), [a2, c, b]);
assert.equal(dedupeById(input, "last")[0], a2);
assert.deepEqual(input, [a1, b, a2, c, b]);
assert.deepEqual(dedupeById([]), []);

const unusual = ["10", "2", "__proto__", "constructor", "01", "1"]
  .map(id => ({ id }));
assert.deepEqual(dedupeById(unusual), unusual);

for (const record of [null, [], {}, { id: "" }, { id: 1 },
                      Object.create({ id: "inherited" })]) {
  assert.throws(() => dedupeById([record]), TypeError);
}
assert.throws(() => dedupeById(null), TypeError);
assert.throws(() => dedupeById([], "latest"), TypeError);
assert.throws(() => dedupeById([a1, { id: "a" }, {}]), TypeError);

console.log("Deduplication checks passed.");

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.