I want to remove an item from a stored array in angular 2, with Type Script. I am using a service called Data Service, the DataService Code:
export cl
Use splice()
to remove item from the array its refresh the array index to be consequence.
delete
will remove the item from the array but its not refresh the array index which means if you want to remove third item from four array items the index of elements will be after delete the element 0,1,4
this.data.splice(this.data.indexOf(msg), 1)
This can be achieved as follows:
this.itemArr = this.itemArr.filter( h => h.id !== ID);
I think the Angular 2 way of doing this is the filter method:
this.data = this.data.filter(item => item !== data_item);
where data_item is the item that should be deleted
You can delete the data from array
this.data.splice(index, 1);
Sometimes, splice is not enough especially if your array is involved in a FILTER logic. So, first of all you could check if your element does exist to be absolute sure to remove that exact element:
if (array.find(x => x == element)) {
array.splice(array.findIndex(x => x == element), 1);
}
Don't use delete
to remove an item from array and use splice()
instead.
this.data.splice(this.data.indexOf(msg), 1);
See a similar question: How do I remove a particular element from an array in JavaScript?
Note, that TypeScript is a superset of ES6 (arrays are the same in both TypeScript and JavaScript) so feel free to look for JavaScript solutions even when working with TypeScript.