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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay