Exercise 1: Remove Duplicates (keep order)

Problem Statement

Create a function `unique(arr)` that removes duplicates but preserves original order.

Sample Output:

unique([1, 2, 2, 3, 1, 4]) => [1, 2, 3, 4]
unique(["a", "b", "a", "c"]) => ["a", "b", "c"]

Solution

const unique = (arr) => {
  const seen = new Set();
  return arr.filter((x) => (seen.has(x) ? false : (seen.add(x), true)));
};

Explanation

Line 1: function header

  • const unique = (arr) => { → ek arrow function bana rahe hain jiska naam unique hai.
  • arr parameter hai: ye wahi input array hoga jisme duplicates ho sakte hain.

Line 2: Set kyu?

  • const seen = new Set(); → yaha Set ek special data structure hai jisme values unique hoti hain.
  • Har value sirf 1 baar store hoti hai, isliye “already dekha hai kya?” check karna super fast ho jata hai.

Line 3: filter ke andar logic

  • return arr.filter((x) => (...))filter har element x ko check karega.
  • seen.has(x) → puch raha hai: kya ye value pehle se seen me hai?
  • Agar seen.has(x) true hai → iska matlab ye duplicate hai → false return, to ye element naya array me nahi aayega.
  • Agar seen.has(x) false hai → to hum (seen.add(x), true) chala rahe hain:
  • seen.add(x) → pehli baar is value ko seen me store karo.
  • , true (comma operator) → last expression true return karta hai, to filter ko true milta hai.
  • true ka matlab: ye element new array me include karo.

Result:

  • Pehli baar aane wali har value add hogi, duplicates skip ho jayenge.
  • Original order bhi same rahega kyunki hum sirf skip kar rahe hain, re‑order nahi.

Real world:

  • Tags list, selected filters, recently viewed products jaha duplicate entries nahi chahiye.

Navigation

Previous

No previous exercise

Next

Exercise 2

View All Categories