Remove duplicates from an array in JavaScript
Beginner · 3 min read
Lists pick up repeats all the time. A user taps the same tag twice, two data sources overlap, a log records the same visitor on every page. Removing duplicates while keeping the original order is one of the most common array jobs there is, and modern JavaScript can do it in one short line.
In this tutorial you will write unique(values) using a Set, then find out exactly what "the same value" means to it. That last part matters more than the one-liner, because it decides what happens with objects. You need to know what an array and an arrow function are.
What a Set is
A Set is a collection that holds each value at most once. Adding a value it already has does nothing.
const tags = new Set();
tags.add('red');
tags.add('blue');
tags.add('red');
console.log(tags.size); // 2
console.log(tags.has('blue')); // true
You can also build a Set straight from an array. The repeats simply don't get in:
console.log(new Set([1, 2, 2, 3])); // Set(3) { 1, 2, 3 }
Turning it back into an array
A Set is not an array, so it has no map or filter. The spread syntax, [...something], walks through any collection and puts its items into a new array:
console.log([...new Set(['a', 'b', 'a'])]); // [ 'a', 'b' ]
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
26 Remove duplicates from a list
easyGiven a list with repeats, produce one with each value appearing once, keeping the original order. Note what "the same" means here.
Stuck? Three hints, smallest first
- 1.
[...new Set(values)]is the whole answer for primitives. - 2.
Setcompares by identity, so two objects with identical contents both survive. - 3.
SettreatsNaNas equal to itself, which===does not.
Step 1: the one-liner
Put the two ideas together:
const unique = (values) => [...new Set(values)];
console.log(unique([1, 2, 2, 3, 1, 4])); // [ 1, 2, 3, 4 ]
console.log(unique(['a', 'b', 'a'])); // [ 'a', 'b' ]
For numbers and strings, that is the whole answer.
Step 2: check the order
A Set remembers the order in which values were first added. So each value stays where it first appeared, and later repeats are dropped:
const unique = (values) => [...new Set(values)];
console.log(unique([3, 1, 3, 2])); // [ 3, 1, 2 ]
3 appears first, so it stays first. Nothing gets sorted.
Step 3: objects are compared by identity
Now try objects. A variable holding an object holds a reference to it, a pointer to one particular object in memory. Two objects can look identical and still be two separate objects:
const unique = (values) => [...new Set(values)];
const shared = { id: 1 };
console.log(unique([shared, shared]).length); // 1: the same object twice
console.log(unique([{ id: 1 }, { id: 1 }]).length); // 2: two objects that look alike
Each { id: 1 } creates a new object. A Set compares objects by identity ("is this the very same object?"), not by contents. So both look-alikes survive. This surprises people when their list comes from an API, where every record is a fresh object.
Step 4: dedupe objects by a key
If you mean "same contents", you have to say which field decides. uniqueBy takes a function, keyOf, that picks that field:
function uniqueBy(values, keyOf) {
const seen = new Map();
for (const v of values) if (!seen.has(keyOf(v))) seen.set(keyOf(v), v);
return [...seen.values()];
}
console.log(uniqueBy([{ id: 1 }, { id: 1 }, { id: 2 }], (o) => o.id));
// [ { id: 1 }, { id: 2 } ]
A Map stores key and value pairs. For each item we work out its key. If we haven't seen that key yet, we store the item under it. The first item with each key wins, and seen.values() gives the kept items back in order.
Step 5: the NaN oddity
NaN means "Not a Number", the result of something like 0 / 0. It has a famous quirk: it is not equal to itself.
const unique = (values) => [...new Set(values)];
console.log(NaN === NaN); // false
console.log(unique([NaN, NaN]).length); // 1
A Set uses a slightly different rule from ===, called SameValueZero, and under that rule NaN does equal NaN. That is the one place where a Set's idea of "the same" differs from ===, and here it is helpful: you get one NaN, not two.
The full solution
The complete answer dedupes numbers and strings, shows that order is kept, compares look-alike objects with the same object twice, adds uniqueBy, and checks the NaN case. Press Run to see the output.
const unique = (values) => [...new Set(values)];
console.log(unique([1, 2, 2, 3, 1, 4]));
console.log(unique(['a', 'b', 'a']));
// Order is preserved: a Set iterates in insertion order.
console.log('order kept:', unique([3, 1, 3, 2]));
// Objects are compared by identity, so look-alikes are not duplicates.
const shared = { id: 1 };
console.log('same object twice :', unique([shared, shared]).length);
console.log('two equal objects :', unique([{ id: 1 }, { id: 1 }]).length);
// To dedupe objects by content, pick a key.
function uniqueBy(values, keyOf) {
const seen = new Map();
for (const v of values) if (!seen.has(keyOf(v))) seen.set(keyOf(v), v);
return [...seen.values()];
}
console.log('deduped by id:', uniqueBy([{ id: 1 }, { id: 1 }, { id: 2 }], (o) => o.id));
// The NaN oddity: Set considers it equal to itself, === does not.
console.log('NaN === NaN :', NaN === NaN);
console.log('unique([NaN,NaN]):', unique([NaN, NaN]).length);
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('numbers deduped', unique([1, 2, 2, 3, 1, 4]), [1, 2, 3, 4]);
test('order is preserved', unique([3, 1, 3, 2]), [3, 1, 2]);
test('the same object twice collapses', unique([shared, shared]).length, 1);
test('two equal objects do not', unique([{ id: 1 }, { id: 1 }]).length, 2);
test('but they do when you name the key', uniqueBy([{ id: 1 }, { id: 1 }, { id: 2 }], (o) => o.id).length, 2);
test('Set treats NaN as one value', unique([NaN, NaN]).length, 1);
test('even though === disagrees', NaN === NaN, false);
Two things worth carrying away. Set deduplicates by identity, so [{id:1}, {id:1}] keeps both — if you meant "same contents" you have to say which field decides, as uniqueBy does. And Set uses SameValueZero, under which NaN equals itself; that is the one place its notion of equality differs from ===.
Common mistakes
- Expecting look-alike objects to merge.
[{ id: 1 }, { id: 1 }]keeps both. Pick a key withuniqueBy. - Returning the Set itself. A Set has no
map,filteror index access like[0]. Spread it back into an array. - Sorting to remove duplicates. It works, but it destroys the original order, which the exercise asks you to keep.
Try it yourself
- Use
uniqueByto remove duplicate emails ignoring case, so'Ada@x.com'and'ada@x.com'count as one. - Write
duplicates(values)that returns only the values that appear more than once. - Change
uniqueByso the last item with each key wins instead of the first.