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
}
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.
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
)
);
}
this.item = this.item.filter((el, i, a) => i === a.indexOf(el))
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