Get unique values from an array in JavaScript
Beginner · 4 min read
Removing duplicates from a list is one of the most searched JavaScript questions. Tags typed twice, the same email address in a mailing list, a product added to a cart twice: you want each value once, in the order you first saw it.
In this tutorial you will do it the modern way with a Set, then the older way with filter and indexOf, and find a value that the older way gets badly wrong. Then you will handle objects, which neither version de-duplicates on its own. You should know arrays, filter and arrow functions.
What a Set is
A Set is a built-in collection that holds each value only once. Add a value it already has and nothing happens. It also remembers the order values were first added.
const s = new Set([1, 2, 2, 3, 1]);
console.log(s.size); // 3
console.log(s.has(2)); // true
console.log(s[0]); // undefined
console.log([...s]); // [ 1, 2, 3 ]
A Set has no indexes, so s[0] is undefined, and it has no array methods like map. Spread, [...s], turns it back into an array.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
37 Unique values
easyRemove duplicates while keeping the first occurrence of each value. Then try it on [NaN, NaN] with both the Set version and the older filter/indexOf one.
Stuck? Three hints, smallest first
- 1. A
Setkeeps insertion order and rejects a value it already holds. - 2. Spread or
Array.fromconverts it back, because aSethas no indexes and no array methods. - 3.
filter((v, i, a) => a.indexOf(v) === i)was the old idiom, andindexOfcannot findNaN.
Step 1: unique values with a Set
Put the list into a Set to drop the repeats, then spread it back into an array.
const unique = (xs) => [...new Set(xs)];
console.log(unique([1, 2, 2, 3, 1])); // [ 1, 2, 3 ]
console.log(unique(['b', 'a', 'b'])); // [ 'b', 'a' ]
The second line shows that order is kept: 'b' came first in the input, so it comes first in the result. The first time a value appears decides its place.
Step 2: the older way
Before Set existed, people wrote this:
const uniqueOldWay = (xs) => xs.filter((v, i, all) => all.indexOf(v) === i);
console.log(uniqueOldWay([1, 2, 2, 3, 1])); // [ 1, 2, 3 ]
filter passes three things to its callback: the value, its index, and the whole array. all.indexOf(v) finds the first position of that value. If that is the current position, this is the first time we've seen it, so keep it. Otherwise it is a repeat, so drop it.
You will still meet this in older code, and on ordinary values it agrees with the Set version.
Step 3: try NaN
NaN means "not a number". It is what you get from things like Number('abc'). It has one famous oddity: it is not equal to itself.
const unique = (xs) => [...new Set(xs)];
const uniqueOldWay = (xs) => xs.filter((v, i, all) => all.indexOf(v) === i);
console.log(NaN === NaN); // false
console.log([NaN].indexOf(NaN)); // -1
console.log(unique([NaN, NaN])); // [ NaN ]
console.log(uniqueOldWay([NaN, NaN])); // []
indexOf compares with ===, so it can never find NaN and always returns -1. Then -1 === i is false for every item, and the older version throws every NaN away. That is not a cosmetic bug: data has gone missing.
A Set compares with a rule called SameValueZero, which is like === except that NaN matches itself. So it keeps one NaN, which is right.
Step 4: zero and minus zero
JavaScript has a -0 as well as 0. A Set treats them as the same value.
const unique = (xs) => [...new Set(xs)];
console.log(unique([0, -0])); // [ 0 ]
Step 5: objects that look the same
const unique = (xs) => [...new Set(xs)];
console.log(unique([{ id: 1 }, { id: 1 }]).length); // 2
Both objects have id: 1, but they are two separate objects. A Set compares objects by identity, meaning "is this the very same object?", not by their contents. So both survive. The older version does the same, for the same reason.
Step 6: unique by a key
When "the same" means "has the same id", compare a key instead of the object. Keep a Set of the keys you have already seen.
function uniqueBy(xs, keyOf) {
const seen = new Set();
return xs.filter((x) => {
const key = keyOf(x);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
const rows = [{ id: 1, n: 'a' }, { id: 2, n: 'b' }, { id: 1, n: 'again' }];
console.log(uniqueBy(rows, (r) => r.id).map((r) => r.n)); // [ 'a', 'b' ]
keyOf is a function you pass in that picks the key from each item. The first record with each id is kept, and the later 'again' record is dropped. Returning false from a filter callback drops the item, and true keeps it.
The full solution
The panel has unique, uniqueOldWay and uniqueBy, and runs them on numbers, NaN and objects. Press Run and compare the two NaN lines.
const unique = (xs) => [...new Set(xs)];
const uniqueOldWay = (xs) => xs.filter((v, i, all) => all.indexOf(v) === i);
// Unique by a computed key, which a Set alone cannot do for objects.
function uniqueBy(xs, keyOf) {
const seen = new Set();
return xs.filter((x) => {
const key = keyOf(x);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
const rows = [{ id: 1, n: 'a' }, { id: 2, n: 'b' }, { id: 1, n: 'again' }];
console.log('unique :', unique([1, 2, 2, 3, 1]));
console.log('order kept :', unique(['b', 'a', 'b']));
console.log('old idiom :', uniqueOldWay([1, 2, 2, 3, 1]));
console.log('--- NaN ---');
console.log('Set :', unique([NaN, NaN]).length, 'value');
console.log('indexOf :', uniqueOldWay([NaN, NaN]).length, 'values <- both dropped');
console.log('--- objects ---');
console.log('two lookalikes stay:', unique([{ id: 1 }, { id: 1 }]).length);
console.log('uniqueBy id :', uniqueBy(rows, (r) => r.id).map((r) => r.n));
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('duplicates are removed', unique([1, 2, 2, 3, 1]), [1, 2, 3]);
test('the first occurrence sets the order', unique(['b', 'a', 'b']), ['b', 'a']);
test('the old idiom agrees on ordinary values', uniqueOldWay([1, 2, 2, 3, 1]), [1, 2, 3]);
test('a Set treats NaN as one value', unique([NaN, NaN]).length, 1);
test('but indexOf cannot find NaN, so the old idiom drops every one', uniqueOldWay([NaN, NaN]), []);
test('0 and -0 are also one value to a Set', unique([0, -0]), [0]);
test('objects are kept by identity, so lookalikes both survive', unique([{ id: 1 }, { id: 1 }]).length, 2);
test('uniqueBy fixes that, keeping the first of each key', uniqueBy(rows, (r) => r.id).map((r) => r.n), ['a', 'b']);
test('a Set has no indexes, which is why you convert back', new Set([1, 2])[0], undefined);
Also Basic 26. The angle here is the comparison each version uses. A Set uses SameValueZero, so NaN equals itself and de-duplicates properly; filter with indexOf uses strict equality, and since indexOf(NaN) is always -1, the condition indexOf(v) === i is false for every NaN and they all vanish. That is a data-loss bug, not a cosmetic one.
Neither version helps with objects, because both compare identity. When "the same" means "the same id", you need a key function — uniqueBy is the smallest thing that works, and it is worth keeping around.
Common mistakes
- Using
filterwithindexOfon data that might holdNaN. EveryNaNdisappears. Use aSet. - Returning the Set itself. It has no indexes or array methods. Spread it back:
[...new Set(xs)]. - Expecting lookalike objects to merge. A Set compares objects by identity. Use a key, as
uniqueBydoes.
Try it yourself
- Get the unique letters in
'mississippi', as a string:'misp'. - Remove duplicate emails from a list, ignoring upper and lower case. (Hint:
uniqueBywithtoLowerCase.) - Change
uniqueByso it keeps the last record for each key instead of the first.