如何在TypeScript中删除数组项?

743

我在TypeScript中创建了一个数组,它有一个属性作为键。如果我拥有这个键,我该如何从数组中删除一个元素?

20个回答

7
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);

6

还有一种使用TypeScript的解决方案:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;

虽然这样解决了问题,但由于创建新数组并循环原始数组,执行起来代价昂贵。在大型数组上执行此类操作可能会产生不良副作用,如对移动电池的影响更大、等待时间长、卡顿等。 - Jessy

6

使用TypeScript扩展操作符(...)进行回答

// 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;

3
function myFunction(ID){ 
let index = this.myArray.findIndex(d => d.ID === ID); //find index in your array
        console.log('index==',index);
        if (index > -1) {
          console.log('remaving at',index);
          this.myArray.splice(index, 1);//remove element from array
        }
}

注意:您的数组必须具有名为ID的属性...否则它将返回-1,表示未找到。


1
_.pull(array,'a'); 

使用lodash库https://lodash.com/docs/4.17.15#pull
完整代码:

import _ from 'lodash';
const allTagList = ['a','b','b']
_.pull(allTagList, b);
console.log(allTagList) // result: ['a']

PS:Lodash提供了许多操作符,建议使用它来简化代码。 https://lodash.com


1
类似于Abdus Salam Azad answer,但是将数组作为参数传递,来自//https://love2dev.com/blog/javascript-remove-from-array/。
function arrayRemove(arr:[], value:any) { 
    
    return arr.filter(function(ele){ 
        return ele != value; 
    });
}

1
这不是“删除一个项目”,而是“创建一个没有该项目的新数组”。完全不同的事情。 - Clashsoft
@Clashsoft,没错,但人们通常更喜欢不可变的调用。如果你想的话,可以将结果重新分配给同一个变量myArr=arrayRemove(myArr, elemToRemove)。 - Michael Freidgeim

1

只是想为数组添加扩展方法。

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
我看到很多人抱怨缺少内置的`remove`方法。考虑使用`Set`代替数组 - 它具有内置的`add`和`delete`方法。

0
我们可以使用 filterincludes 来实现该逻辑。

const checkAlpha2Code = ['BD', 'NZ', 'IN']

let countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']


/**
 * Returns the modified array countryAlpha2Code 
 * after removing elements which matches with the checkAlpha2Code
 */
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
    return !checkAlpha2Code.includes(alpha2code);
});
console.log(countryAlpha2Code)
// Output: [ 'US', 'CA', 'AF', 'AR', 'BR' ]


// Resetting the values again
countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']


/**
 * Returns the modified array countryAlpha2Code 
 * which only matches elements with the checkAlpha2Code
 */
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
    return checkAlpha2Code.includes(alpha2code);
});

console.log(countryAlpha2Code)
// Output: [ 'BD', 'NZ' ]


0

你可以先尝试获取列表或数组的索引或位置,然后使用for循环将当前数组分配给临时列表,过滤掉不需要的项目并将所需项目存储回原始数组

removeItem(index) {
    var tempList = this.uploadFile;
    this.uploadFile = [];

    for (var j = 0; j < tempList.length; j++) {
      if (j != index)
        this.uploadFile.push(tempList[j]);
    }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接