How do I remove an array item in TypeScript?

后端 未结 14 2280
渐次进展
渐次进展 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 08:04

    One more solution using Typescript:

    let updatedArray = [];
    for (let el of this.oldArray) {
        if (el !== elementToRemove) {
            updated.push(el);
        }
    }
    this.oldArray = updated;
    
    0 讨论(0)
  • 2020-12-07 08:05

    Answer using TypeScript spread operator (...)

    // Your key
    const key = 'two';
    
    // Your array
    const arr = [
        'one',
        'two',
        'three'
    ];
    
    // Get either the index or -1
    const index = arr.indexOf(key); // returns 0
    
    
    // Despite a real index, or -1, use spread operator and Array.prototype.slice()    
    const newArray = (index > -1) ? [
        ...arr.slice(0, index),
        ...arr.slice(index + 1)
    ] : arr;
    
    0 讨论(0)
  • 2020-12-07 08:07

    Just wanted to add extension method for an array.

    interface Array<T> {
          remove(element: T): Array<T>;
        }
    
        Array.prototype.remove = function (element) {
          const index = this.indexOf(element, 0);
          if (index > -1) {
            return this.splice(index, 1);
          }
          return this;
        };
    
    0 讨论(0)
  • 2020-12-07 08:08

    Here's a simple one liner for removing an object by property from an array of objects.

    delete this.items[this.items.findIndex(item => item.item_id == item_id)];
    

    or

    this.items = this.items.filter(item => item.item_id !== item.item_id);
    
    0 讨论(0)
  • 2020-12-07 08:12

    Use this, if you need to remove a given object from an array and you want to be sure of the following:

    • the list is not reinitialized
    • the array length is properly updated
        const objWithIdToRemove;
        const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
        if (objIndex > -1) {
          this.objectsArray.splice(objIndex, 1);
        }
    
    0 讨论(0)
  • 2020-12-07 08:12
    let a: number[] = [];
    
    a.push(1);
    a.push(2);
    a.push(3);
    
    let index: number = a.findIndex(a => a === 1);
    
    if (index != -1) {
        a.splice(index, 1);
    }
    
    console.log(a);
    
    0 讨论(0)
提交回复
热议问题