How do I remove an array item in TypeScript?

后端 未结 14 2279
渐次进展
渐次进展 2020-12-07 07:42

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?

相关标签:
14条回答
  • 2020-12-07 07:57

    With ES6 you can use this code :

    removeDocument(doc){
       this.documents.forEach( (item, index) => {
         if(item === doc) this.documents.splice(index,1);
       });
    }
    
    0 讨论(0)
  • 2020-12-07 07:57

    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"]
    
    0 讨论(0)
  • 2020-12-07 07:58

    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();
    }
    
    0 讨论(0)
  • 2020-12-07 07:58

    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]);
        }
      }
    
    0 讨论(0)
  • 2020-12-07 08:03

    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);}
    
    0 讨论(0)
  • 2020-12-07 08:04

    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);
    }
    
    0 讨论(0)
提交回复
热议问题