skip to content
Slashism

Remove Duplicates from a JavaScript Array

/ 1 min read

This is one of the questions that I used to ask in interviews. I was also asked this question initially when I started my career as a software engineer.

It’s a very simple problem yet surprisingly many fails to answer it. I know because I have asked many candidates and not all of them were able to answer correctly.

There are many ways to do this. So let’s take a look at the different ways to do it one by one:

Using Set (My favorite way)

It is the shortest way to achieve this:

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

Using indexOf() and loop

const colors = [
'red',
'blue',
'green',
'red',
'blue'
];
const uniqueColors = [];
for (let color of colors) {
if(uniqueColors.indexOf(color) === -1) {
uniqueColors.push(color);
}
}
console.log(uniqueColors);

Using indexOf() and filter

const colors = [
'red',
'blue',
'green',
'red',
'blue'
];
const uniqueColors = colors.filter((color, index) => colors.indexOf(color) === index);
console.log(uniqueColors);

Using forEach() and include()

const colors = [
'red',
'blue',
'green',
'red',
'blue'
];
const uniqueColors = [];
colors.forEach((color) => {
if (!uniqueColors.includes(color)) {
uniqueColors.push(color);
}
});
console.log(uniqueColors);

I hope this was useful for you!

Thanks for reading!