Remove duplicated values from array in JavaScript
There are several ways to reduce the duplicated values in array.
I will introduce the one-liner code here.
Before jumping into the solution, you need to know about Set first.
What is Set in JavaScript?
A JavaScript Set is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type.
Let’s see through examples.
const mySet = new Set();
mySet.add(10); // size: 1, entries : 10
mySet.add(20); // size: 2, entries : 10, 20
mySet.add(30); // size: 3, entries : 10, 20, 30
mySet.add(10); // 10 never added again. mySet still contains 10, 20, 30
// size: 3That’s because Set is a collection of unique values.
Get John Alim’s stories in your inbox
Join Medium for free to get updates from this writer.
But there is something to remember.
The Set isn’t a collection of unique objects.
const mySet = new Set();
mySet.add({ key: 'first', value: 0}); // size: 1, SUCCESS
mySet.add({ key: 'first', value: 0}); // size: 2, SUCCESS
mySet.add({ key: 'first', value: 0}); // size: 3, SUCCESSLook over the console.
Remove duplicated values from array.
- Solution in case array of values
const array = [10, 20, 30, 10, 20];
const uniqArray= [...new Set(array)];
// uniqArray: [10, 20, 30]- Solution in case array of objects
const array = [
{
key: 'first', value; 0
},
{
key: 'first', value; 0
},
{
key: 'second', value; 1
}
];
const uniqArray = Array.from(new Set(array.map(item => item.id)))
.map(id => {
return array.find(v => v.id === id)
});
/**
* uniqArray: [
* {
* key: 'first', value; 0
* },
* {
* key: 'second', value; 1
* }
* ]
*/
There are more good ways to do using array.filter, array.reduce.
Hope this would be helpful.
Thanks for your reading.



