Skip to content

Avoiding Duplicate Array Values

An array accepts the same value as many times as it is added. Where each value should appear once, there are two jobs: removing the duplicates from an array that already has them, and building an array so that duplicates never get in.

A Set holds each value only once. Passing an array to new Set() drops the repeats, and spreading the set back into an array literal gives an array again:

const tags = ['red', 'blue', 'red', 'green', 'blue'];
const unique = [...new Set(tags)];
console.log(unique);

This prints:

[ 'red', 'blue', 'green' ]

The values keep the order in which each first appeared. This is the shortest and, for large arrays, the fastest way to remove duplicates. Maps and Sets covers Set in more detail.

The same result can be had with filter(), which keeps an item only where its index is the first index at which that value appears:

const tags = ['red', 'blue', 'red', 'green', 'blue'];
const unique = tags.filter((tag, index) => tags.indexOf(tag) === index);
console.log(unique);

This prints:

[ 'red', 'blue', 'green' ]

This version searches the array once for every item, so it slows down quickly as the array grows. It is worth knowing because it shows the idea, but the Set is the better choice.

Both approaches compare objects by reference, so two separate objects with the same properties count as different values. To remove duplicates among objects, choose the property that identifies a record and key on it. A Map keyed on that property keeps one record per key:

const users = [
{ id: 7, name: 'Ana' },
{ id: 9, name: 'Ben' },
{ id: 7, name: 'Ana' },
];
console.log(new Set(users).size);
const byId = new Map(users.map((user) => [user.id, user]));
console.log([...byId.values()]);

This prints:

3
[ { id: 7, name: 'Ana' }, { id: 9, name: 'Ben' } ]

Where two records share a key, the Map keeps the later record in the earlier record’s position.

When the values arrive one at a time, check before adding. includes() reports whether the array already holds the value:

const seen = [];
for (const n of [3, 8, 3, 5, 8]) {
if (!seen.includes(n)) {
seen.push(n);
}
}
console.log(seen);

This prints:

[ 3, 8, 5 ]

A Set does the same check for you, because add() ignores a value it already holds. That makes it a good fit for generating random numbers without repeats, such as six lottery numbers between 1 and 49:

const min = 1;
const max = 49;
const picks = new Set();
while (picks.size < 6) {
const n = Math.floor(Math.random() * (max - min + 1)) + min;
picks.add(n);
}
console.log([...picks].sort((a, b) => a - b));

One run printed:

[ 22, 27, 29, 37, 38, 47 ]

The loop keeps going until the set holds six values, so a repeated number simply costs one more pass. The compare function in sort() is needed for numbers, as Custom Array Sorts explains.

To draw several items at random from a list, such as raffle winners, take each pick out of a copy of the list so it cannot be drawn again:

const raffle = ['Ana', 'Ben', 'Chloe', 'Dev', 'Esme'];
const pool = [...raffle];
const winners = [];
while (winners.length < 3) {
const pick = Math.floor(Math.random() * pool.length);
winners.push(...pool.splice(pick, 1));
}
console.log(winners);
console.log(raffle);

One run printed:

[ 'Dev', 'Ben', 'Chloe' ]
[ 'Ana', 'Ben', 'Chloe', 'Dev', 'Esme' ]

splice() removes the chosen item from pool and returns it in an array, which the spread passes to push(). Working on a copy leaves the original list unchanged.

Steve Griffith covers this topic in his video Avoiding Duplicate Array Values.