I have an array that I\'ve created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?
With ES6 you can use this code :
removeDocument(doc){
this.documents.forEach( (item, index) => {
if(item === doc) this.documents.splice(index,1);
});
}
You can use the splice
method on an array to remove the elements.
for example if you have an array with the name arr
use the following:
arr.splice(2, 1);
so here the element with index 2 will be the starting point and the argument 2 will determine how many elements to be deleted.
If you want to delete the last element of the array named arr
then do this:
arr.splice(arr.length-1, 1);
This will return arr with the last element deleted.
Example:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
It is my solution for that:
onDelete(id: number) {
this.service.delete(id).then(() => {
let index = this.documents.findIndex(d => d.id === id); //find index in your array
this.documents.splice(index, 1);//remove element from array
});
event.stopPropagation();
}
You can try to get index or position of list or array first, then use for loop to assign current array to a temp list, filter out unwanted item and store wanted item back to original array
removeItem(index) {
var tempList = this.uploadFile;
this.uploadFile = [];
for (var j = 0; j < tempList.length; j++) {
if (j != index)
this.uploadFile.push(tempList[j]);
}
}
This Worked for me
Your Array :
DummyArray: any = [
{"id": 1, "name": 'A'},
{"id": 2, "name": 'B'},
{"id": 3, "name": 'C'},
{"id": 4, "name": 'D'}]
Function:
remove(){
this.DummyArray = this.DummyArray.filter(item => item !== item);}
Note: This function deletes all the objects form your array. If you want to delete a specific object from array then use this method:
remove(id){
this.DummyArray = this.DummyArray.filter(item => item.id !== id);}
Same way as you would in JavaScript.
delete myArray[key];
Note that this sets the element to undefined
.
Better to use the Array.prototype.splice function:
const index = myArray.indexOf(key, 0);
if (index > -1) {
myArray.splice(index, 1);
}