我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
我们可以使用筛选器和包含来实现逻辑
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' ]
其他回答
_.pull(array,'a');
使用lib lodash https://lodash.com/docs/4.17.15#pull complelte代码:
import _ from 'lodash';
const allTagList = ['a','b','b']
_.pull(allTagList, b);
console.log(allTagList) // result: ['a']
PS: Lodash提供了大量的操作符,建议使用它来简化您的代码。https://lodash.com
这是我的解决方案:
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();
}
可以在数组上使用splice方法删除元素。
例如,如果你有一个名为arr的数组,使用以下方法:
arr.splice(2, 1);
因此,这里索引为2的元素将是起点,参数2将决定删除多少个元素。
如果你想删除名为arr的数组的最后一个元素,那么这样做:
arr.splice(arr.length-1, 1);
这将返回删除最后一个元素的arr。
例子:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
使用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;
Let departments是一个数组。您要从此数组中删除一项。
departments: string[] = [];
removeDepartment(name: string): void {
this.departments = this.departments.filter(item => item != name);
}
推荐文章
- 从元组/数组值派生联合类型
- 如何在Angular2 ngSwitch语句中使用typescript enum值
- 使用C返回一个数组
- 如何检查IEnumerable是否为空或空?
- 找到合成属性@panelState。请在您的应用程序中包含“BrowserAnimationsModule”或“NoopAnimationsModule”。
- 向对象数组添加属性
- Angular 2+和debounce
- JavaScript在数组中
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- 在TypeScript箭头函数中指定返回类型
- 如何使用jQuery与TypeScript
- 使用lodash将对象转换为数组
- 从数组中随机选择一个元素
- Angular 2模板中的标签是什么意思?