DEV Community

Paramanantham Harrison for JS Mates

Posted on • Originally published at jsmates.com on

How to remove duplicates in an array using JS Set?

Consider we have an simple string array with duplicate values,

const authorNames = [
  'Param',
  'Moises',
  'Fernando',
  'Joshua',
  'Param',
  'Joshua'
];
Enter fullscreen mode Exit fullscreen mode

The array have Param and Joshua values duplicated twice. There are several ways to remove duplicates, using Set is just one among them.

const uniqueAuthorNames = [...new Set(authorNames)];
console.log(uniqueAuthorNames); // Output - ["Param", "Moises", "Fernando", "Joshua"] ✅
Enter fullscreen mode Exit fullscreen mode

What if the data is an array of objects?

We can make it work, but directly using Set on the array of objects won't work.

const authors = [
  {
    name: 'Param',
    age: 30
  },
  {
    name: 'Joshua',
    age: 26
  },
  {
    name: 'Param',
    age: 30
  }
];
const uniqueAuthors = [...new Set(authors)];
console.log(uniqueAuthors); // Output - It won't remove the duplicates ❌
Enter fullscreen mode Exit fullscreen mode

Top comments (0)