Skip to the solution
EasyDSA6 min read

Implement dedupe / unique — remove duplicates preserving order

112 views

The problem

Problem, as an interviewer would state it: "Implement dedupe(array) — removing every duplicate value while preserving the original, real first-occurrence order of each unique element."

Examples:

Code
dedupe([3,1,2,3,1,4,2]); // [3,1,2,4]

Clarifying questions expected:

  • Does the real ORDER of the surviving unique elements need to genuinely match their FIRST occurrence in the input, or is any order acceptable?
  • What comparison algorithm should genuinely determine "duplicate" — should a real NaN be treated as a duplicate of another NaN?
  • Is a one-line [...new Set(array)] an acceptable, real, idiomatic solution, or does the interviewer want the underlying mechanism demonstrated explicitly?

Code / implementation expected: Yes — real, direct proof of order preservation, plus a real, direct demonstration of the underlying comparison algorithm's edge cases (NaN, +0/-0).

  • array
  • dedupe
  • set

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: dedupe() preserves first-occurrence order, and correctly treats a real NaN and +0/-0 as duplicates via Set's SameValueZero comparison

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 44 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement curry(fn) That Supports Any Call Pattern — curry(1)(2)(3), curry(1,2,3), or curry(1,2)(3)

Continue