I'm struggling with something that should be very simple. I have an array of objects. I need to remove duplicate from this array based on the id
property. So I want to create a Set
containing my ids, like this:
let myArray = [{
id: 10,
other: "bla"
},
{
id: 15,
other: "meh"
},
{
id: 10,
other: "bla"
}
]
let indexes = new Set();
myArray.forEach(a => indexes.add(a.id));
console.log('indexes list', indexes)
But indexes
is always empty. What am I doing wrong? Thanks.
EDIT: I chose @Hyyan Abo Fakher's as correct answer because he was right, but the suggestion in @bambam comment was a great solution to the whole problem. Thanks to everyone.
You could use filter
method with Set
to create new array of unique objects by id
.
const data = [{id: 10, other: "bla"},{id: 15, other: "meh"},{id: 10, other: "bla"}]
let result = data.filter(function({id}) {
return !this.has(id) && this.add(id);
}, new Set)
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With