JavaScript
Deduplicate objects by ID with a JavaScript Map
Use a Map keyed by a stable identifier to keep one record per ID. Reassigning an existing key replaces its value without moving that key to a new insertion position.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const rows = [{id: 2, label: "old"}, {id: 1, label: "first"}, {id: 2, label: "new"}];
const unique = [...new Map(rows.map(row => [row.id, row])).values()];
console.log(JSON.stringify(unique));How it works
Each row becomes a key-value pair. The last row for ID 2 replaces the earlier row, but ID 2 stays before ID 1 in the output. This is useful when a later record represents an update rather than another entity.
Limits and mistakes
Missing IDs all share the undefined key and collapse together. Numeric 2 and string "2" are different keys. Validate or normalize identifiers first, and document whether the first or last record should win.
Check the result
Confirm that ID 2 has label new and still comes first. Add a duplicate with conflicting fields to check the intended replacement rule.
Sources
Reference documentation for the behavior used in this guide: