Remove Duplicates from a JavaScript Array

Remove Duplicates from a JavaScript Array

This is one of my favorite questions that I ask in my interviews. I was also asked this question initially when I started my career as a web dev.

It's a very simple problem yet surprisingly, many fail to answer. 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 you find this useful!

Thanks for reading!