How do you remove duplicate values from an array?
The shortest way is [...new Set(arr)], because a Set stores each value once and keeps insertion order. Filtering with indexOf also works but is slower. For objects, dedupe by a key using a Map.
Explain it simply
Think of a cricket team sheet where a name may be written twice by mistake. A Set is a list that refuses to hold the same value twice, so pouring the array into a Set and back removes duplicates in one step, keeping the first appearance order.
The older approach keeps an item only if its first position equals its current position: arr.filter((x, i) => arr.indexOf(x) === i). That works, but it scans the array for every item.
For an array of objects, a Set compares by reference, so dedupe by an id instead: build a Map from id to object and take its values.
Line by line
const ids = [3, 1, 3, 2, 1];
console.log([...new Set(ids)]); // Output: [3,1,2]
console.log(ids.filter((x, i) => ids.indexOf(x) === i)); // Output: [3,1,2]
const students = [{ id: 1, n: "A" }, { id: 2, n: "B" }, { id: 1, n: "A" }];
const unique = [...new Map(students.map((s) => [s.id, s])).values()];
console.log(unique.length); // Output: 2What to say in the interview
"I use [...new Set(arr)] for primitives. It is O(n) and keeps first-seen order. For objects I dedupe on a key by storing them in a Map keyed by id. The indexOf filter works but is O(n squared)."
Complexity
Set version: time O(n), space O(n). The indexOf filter version: time O(n squared), space O(n).
Common mistakes
- Expecting a Set to treat two objects with equal content as the same. They are different references.