Pankaj Sanam
Slashism

Slashism

Remove Duplicates from a JavaScript Array

Remove Duplicates from a JavaScript Array

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

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!

 
Share this

Impressum

🙋‍♂️ Hello there,

My name is Pankaj, and I am the author of Slashism. I hope that you learn something useful today.

If you like my content and want to stay updated then subscribe to my newsletter in the header.

You can also follow me on Twitter and say hello.

If you would like to request a particular article/topic covered or would want to discuss something, then please start a discussion here on Github Discussions

⭐ Keep learning, keep growing ⭐

Proudly part of