How to remove duplicates in an Array using ES 2015
JavaScript
—
2021-01-24
Have you ever wanted to get distinct values from an array in JavaScript? This small solution will show you how you remove duplicates and get a unique array using ES 2015.
Imagine that you have the following array:
const array = [1, 2, 2, 1, 3, 1, 2, 3, 4];
And you want it to become this:
[1, 2, 3, 4]
Let me introduce new Set()
!
Set is a data object introduced in ES 2015, which lets you store values of any type. A value in the Set may only occur once, making it perfect for what we are trying to accomplish.
Now back to the array we started with.
const array = [1, 2, 2, 1, 3, 1, 2, 3, 4];
Let's create a new Set out of it.
Notice how the Set object already made the values unique.
const array = [1, 2, 2, 1, 3, 1, 2, 3, 4];
const set = new Set(array);
//=> Set {1, 2, 3, 4}
Now convert it back to an array by using the spread operator (...)
.
Your array is now distinct, with only unique values!
const set = new Set(array);
//=> Set {1, 2, 3, 4}
const uniqueArray = [...set];
//=> [1, 2, 3, 4]
This can also be done in a one-liner:
const uniqueArray = [...new Set(array)];
//=> [1, 2, 3, 4]
It can also be used in more advanced cases, for example with an array of objects.
In this example you'll get an array with the cities only mentioned once.
const persons = [{
name: 'Sven',
city: 'Stockholm'
}, {
name: 'Lars',
city: 'Gothenburg'
}, {
name: 'Anna',
city: 'Gothenburg'
}];
const distinctCities = [...new Set(persons.map(person => person.city))];
//=> ['Stockholm', 'Gothenburg']