Remove Duplicate Objects by ID in JavaScript
Keep one record per ID. Choose whether the first or last record wins.
The live editor loads here with JavaScript enabled.
Run in Playground ↗The original source and explanation are available below.
Changes here stay separate from your main playground. Use Open in TryJS inside the editor to keep working with your changes.
Useful? Help keep TryJS free and independent.
Support TryJSWhat to expect
The first result keeps the updated record for ID 1. The second keeps the original record. Both contain two unique IDs.
About this example
API responses and imported lists can contain repeated records. A Set compares object identity, so two objects with the same ID still count as different values. A Map lets you choose a meaningful key and decide which duplicate to keep.
How It Works
Choose the identity
Each Map entry uses record.id as its key. Repeated IDs replace the previous value, preserving the last record for that key.
Keep the first match
Only insert a record when its ID is absent. This keeps the first value instead. Change the key to email or another field to match your data.
Things to watch for
- Using new Set(records) compares object references, not their ID fields.
- Treating missing IDs as unique: all undefined keys collapse into one Map entry.
Read the original source
This is the starting code. Your edits stay in the live editor above.
JavaScript
const records = [
{ id: 1, name: "Original" },
{ id: 1, name: "Updated" },
{ id: 2, name: "Another" },
];
const keepLast = [...new Map(records.map(record => [record.id, record])).values()];
console.log("Last record wins:", keepLast);
const firstById = new Map();
for (const record of records) {
if (!firstById.has(record.id)) firstById.set(record.id, record);
}
console.log("First record wins:", [...firstById.values()]);