我在TypeScript中创建了一个数组,它有一个属性作为键。如果我拥有这个键,我该如何从数组中删除一个元素?
我在TypeScript中创建了一个数组,它有一个属性作为键。如果我拥有这个键,我该如何从数组中删除一个元素?
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);
还有一种使用TypeScript的解决方案:
let updatedArray = [];
for (let el of this.oldArray) {
if (el !== elementToRemove) {
updated.push(el);
}
}
this.oldArray = updated;
使用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;
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,表示未找到。
_.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
function arrayRemove(arr:[], value:any) {
return arr.filter(function(ele){
return ele != value;
});
}
只是想为数组添加扩展方法。
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;
};
filter
和 includes
来实现该逻辑。
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' ]
你可以先尝试获取列表或数组的索引或位置,然后使用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]);
}
}