DEV Community

Discussion on: Removing duplicates in an Array of Objects in JS with Sets

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I have also this solution O.o

const dupAddress = [
    {
        id: 1,
        name: 'Istanbul'
    },
    {
        id: 2,
        name: 'Kocaeli'
    },
    {
        id: 3,
        name: 'Ankara'
    },
    {
        id: 1,
        name: 'Istanbul'
    }
]

let addresses = [...new Set([...dupAddress.map(address => dupAddress[address.id])])]

console.log(addresses)
Enter fullscreen mode Exit fullscreen mode

But this only works with address.id, so this doesn't work with address.name

Really, why this doesn't work like that?

let addresses = [...new Set([...dupAddress.map(address => dupAddress[address.name])])]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
marinamosti profile image
Marina Mosti

Well, you're passing [address.id] as an index to the dupAddress array, that's just not going to work because the id !== index. Try changing it to address.id or address.name without accessing the array

Collapse
 
itachiuchiha profile image
Itachi Uchiha • Edited

Okay, I tried it didn't work actually I was wonder why that didn't work. Thanks.

Collapse
 
waqasongithub profile image
waqas
let addresses = [...new Set([...dupAddress.map(address => dupAddress[address.name])])]

Enter fullscreen mode Exit fullscreen mode