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 naamuniquehai.arrparameter hai: ye wahi input array hoga jisme duplicates ho sakte hain.
Line 2: Set kyu?
const seen = new Set();→ yahaSetek 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) => (...))→filterhar elementxko check karega.seen.has(x)→ puch raha hai: kya ye value pehle seseenme hai?- Agar
seen.has(x)true hai → iska matlab ye duplicate hai →falsereturn, 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 koseenme store karo., true(comma operator) → last expressiontruereturn karta hai, tofilterkotruemilta hai.trueka 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