Sets remove repeated primitive values or repeated references. Business-record deduplication normally requires an explicit key and a conflict policy.
Step-by-step walkthrough
Step 1: Define the duplicate key
A duplicate is a domain decision. For records, choose a validated ID or a documented combination of fields. A Set of object references only identifies repeated references; it does not compare the contents of independently created records.
Step 2: Choose which record wins
First-wins preserves the first occurrence; last-wins incorporates later updates. Decide before coding, because both produce apparently deduplicated output but different data. Preserve output order according to the same declared policy rather than relying on an accidental implementation detail.
Step 3: Handle invalid identifiers
Missing or malformed keys should not silently collapse unrelated records. Reject them, keep them separately or generate a deliberately scoped identity. The deduplication step should make malformed input visible instead of using undefined as a shared business identifier.
Worked scenario
Two separate {id: 1} objects both remain in a Set. Deduplicate their IDs instead.
function firstById(records) {
const seen = new Set();
return records.filter(record => {
if (typeof record.id !== 'string') throw new Error('Invalid ID');
if (seen.has(record.id)) return false;
seen.add(record.id);
return true;
});
}
console.log(firstById([{id:'a'}, {id:'a'}, {id:'b'}]).length); // 2Walk through the example
Each accepted ID enters seen once. Later records with that ID are filtered out, so input order and the first record’s fields survive. The function returns a new array but shares retained record objects; callers requiring independent mutable snapshots need a separate copying policy.
Common mistake
A concise deduplication expression can obscure whether first or last duplicates win.
Verify the behavior
Use repeated IDs with conflicting names to confirm first-wins behavior. Include an empty list, all duplicates, all unique entries and a missing ID. Check that input records are not modified and that key normalization is consistent with the application’s identity rules.
Interview exercise
Keep the first record per ID.
Answer and reasoning
Track IDs in a Set and append unseen records in input order; reject or separately handle missing IDs.
Follow-up discussion
Can a Set deduplicate nested records deeply? Not by itself: object entries use identity. What if the newest version should win? Compare a real version or timestamp through a keyed aggregation; input arrival order is not always the same as business recency.
Continue learning
Compare the scenario with the JavaScript interview questions and test your understanding with the JavaScript MCQs. For terminology and implementation details, consult the reference material.