How to remove duplicates in an array using JS Set?
Paramanantham Harrison
Posted on November 17, 2020
Consider we have an simple string array with duplicate values,
const authorNames = [
'Param',
'Moises',
'Fernando',
'Joshua',
'Param',
'Joshua'
];
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"] ✅
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 ❌
💖 💪 🙅 🚩
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
javascript Day 86 of 100 Days of Code & Scrum: SELECT Within SELECT, Aggregate Functions In SQL, and Other Stuff
January 27, 2022