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
}
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
)
);
}