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 ❌
Top comments (0)