Sitemap
John Alim

John Alim

Senior Full Stack Engineer

Remove duplicated values from array in JavaScript

2 min readDec 14, 2022

--

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: 3

That’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, SUCCESS

Look 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.

--

--

John Alim
John Alim

Written by John Alim

0 followers

Senior Full Stack Engineer