Interview preparation
Intermediate·Coding·2 min read

How do you remove duplicate IDs from an array?

Practice this question

Given the primitive IDs [1, 2, 1, 3], remove duplicates while preserving the order of first occurrence. How would the equality rule differ for objects?

Short explanation:

Deduplication removes repeated values according to a defined equality rule. JavaScript Set handles primitive IDs conveniently and keeps the order of first insertion. Objects are compared by reference, so deduplicating records by an id field requires an explicit key-based approach.

Example and explanation:

JavaScript
const uniqueIds = [...new Set([1, 2, 1, 3])];
// [1, 2, 3]
  • Set keeps one copy of each value and preserves insertion order.

  • For objects, compare a stable field such as id; different objects are different references.

  • Decide whether the first or last record should win when objects share an ID but have different fields.

Interview point:

  • State the equality and ordering requirement before choosing Set or Map.
Adapted from 12_FINAL_MOCK_INTERVIEW.md · “Round 6: How do you remove duplicate IDs from an array?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.