Files and data

Compare lists while preserving duplicate counts

Count occurrences with a Map when repeated entries are meaningful. A set comparison cannot distinguish one copy of an ID from several copies of the same ID.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function counts(values) {
  const result = new Map();
  for (const value of values) result.set(value, (result.get(value) ?? 0) + 1);
  return result;
}
const left = counts(["a", "a", "b"]);
const right = counts(["a", "b", "b"]);
console.log((left.get("a") ?? 0) - (right.get("a") ?? 0));
console.log((left.get("b") ?? 0) - (right.get("b") ?? 0));

How it works

Each map stores a frequency rather than only membership. Subtracting right from left reports a surplus on the left as positive and a deficit as negative. This is useful for reconciliation where duplicates represent quantities or repeated events.

Limits and mistakes

The key still needs a clear equality rule. Objects compare by reference unless you extract a stable identifier. A frequency difference says nothing about which specific repeated row should be removed if other fields differ.

Check the result

Expect 1 and -1. Check absent keys and identical input lists. Label the sign convention in the report so readers do not reverse the direction.

Sources

Reference documentation for the behavior used in this guide: