FrontendPro

16Remove duplicate items from an array

easyAbout 15 minutesCodingarrayssethash-map

Problem

Implement unique(array, getKey). It returns a new array without duplicates, keeping the first occurrence of each item in its original position. The optional getKey(item) decides what counts as "the same", for example an id.

unique([3, 1, 3, 2, 1]); // [3, 1, 2]
unique([NaN, NaN, 0, -0]); // [NaN, 0]
unique(users, (user) => user.id); // first user per id

Requirements

  • Keep the order of first occurrences.
  • Treat NaN as equal to NaN, and 0 as equal to -0.
  • Keep 1 and "1" apart.
  • Objects are compared by reference unless getKey is given.
  • Do not change the input. Solve it in O(n) time.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

[...new Set(array)] removes duplicates and keeps first occurrences, because a Set remembers insertion order. It covers the basic case; the getKey option needs a little more.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever