2dbi

Remove Duplicates From an Array

viaLeetCode

Problem Remove duplicate values from a JavaScript array; compare multiple implementations and their trade-offs.

Input / Output

  • Input: array (primitives; discuss objects separately). Output: new deduped array, order preserved.

Constraints

  • Arrays up to 10^6 elements — O(n) approaches matter; O(n^2) ones must be identified as such.

Example

  • [1, 2, 2, "2", 3, 1] → [1, 2, "2", 3] (Set uses SameValueZero — types matter).

Expected approach

  • [...new Set(arr)] — idiomatic, O(n), insertion-ordered; the expected first answer.
  • arr.filter((x, i) => arr.indexOf(x) === i) — O(n^2) (indexOf scans); fine for tiny arrays, name the cost.
  • reduce with a seen map/Set — O(n), shows mechanics explicitly; also the shape that extends to dedupe-by-key for OBJECTS (Set of ids), since Set on objects compares references, not contents.
  • Probes: NaN behavior (Set keeps one NaN; indexOf misses NaN entirely), +0/−0, dedupe by custom equality, and in-place dedupe of a SORTED array with two pointers (the classic language-agnostic variant).
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account