Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates using Set in Javascript

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.

like image 418
esseara Avatar asked Jul 25 '18 11:07

esseara


1 Answers

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)
like image 172
Nenad Vracar Avatar answered Oct 02 '22 03:10

Nenad Vracar