How to remove duplicates in an array using JS Set?

learnwithparam

Paramanantham Harrison

Posted on November 17, 2020

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

💖 💪 🙅 🚩
learnwithparam
Paramanantham Harrison

Posted on November 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related