6

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.

esseara
  • 834
  • 5
  • 27
  • 47

4 Answers4

9

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
2

But indexes is always empty. What am I doing wrong?

Your code is completely functional, the issue seems to come from the browser console itself, you expect that printing the set to the console will print the items of the set as in arrays but in fact, the browser will print only the object instance

Running your code on StackOverflow will print indexes list {}, but in fact, the browser console printed something else.

enter image description here

To make sure the list is not empty use the size property

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.size)

To loop over the set you need to use for ... of

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));
for (let item of indexes) console.log(item);
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
1

You may check if the set has the ID, and if its not, then push the element to a new array. The final array will have the unique elements.

var source = [
  {id: 10, other: "bla"},
  {id: 15, other: "meh"},
  {id: 10, other: "bla"}
];

var set = new Set();
var result = [];

source.forEach(item => {
  if (!set.has(item.id)) {
    set.add(item.id);
    result.push(item);
  }
})

console.log(result);
31piy
  • 23,323
  • 6
  • 47
  • 67
1

Simply we can use arrays to resolve this issue with help of loop. like below:

var b = [];
a.forEach(function(index){
   if(b[index.id]==undefined){
       b[index.id] = index.other;
   }
});
console.log(b);

Here a is the original source array.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67