Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate object from an array in angular 6

I am trying to remove duplicate value objects in an array but not working... I think duplicate function is working but not reflecting in li list. Can you find out where I have to change?

My service file:

 addComp(Names,c){   
 this.item.push({ name: Names, componentid: c});
 this.uniqueArray = this.removeDuplicates(this.item, "name"); //this line issue
 this.item=this.uniqueArray; //this line issue
 }
like image 906
SRANSV Avatar asked Dec 05 '18 17:12

SRANSV


People also ask

How do you remove duplicates from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.


2 Answers

If addComp is the only place you modify this.item, just check for existing prior to insertion. Duplicates will never get put in the array, so you'll never have to trim them.

addComp(Names,c){
  let item = {name: Names, componentid: c};
  if (this.item.find((test) => test.name === Names) === undefined) {
    this.item.push(item);
  }
}

Alternatively, if there are other places that you're modifying this.item, you should be stripping duplicates in a more expected place. Stripping them as a side-effect of the addComp function is unexpected. However, you could do it...

addComp(Names,c){
  this.item.push({name: Names, componentid: c});
  this.item = this.item.filter((test, index, array) =>
     index === array.findIndex((findTest) =>
        findTest.name === test.name
     )
  );
}
like image 144
Ian MacDonald Avatar answered Oct 24 '22 15:10

Ian MacDonald


this.item = this.item.filter((el, i, a) => i === a.indexOf(el))
like image 30
user2642281 Avatar answered Oct 24 '22 15:10

user2642281