【发布时间】:2013-02-23 21:30:26
【问题描述】:
我有一个我在 TypeScript 中创建的数组,它有一个我用作键的属性。如果我有那个密钥,我怎样才能从中删除一个项目?
【问题讨论】:
标签: arrays typescript collections
我有一个我在 TypeScript 中创建的数组,它有一个我用作键的属性。如果我有那个密钥,我怎样才能从中删除一个项目?
【问题讨论】:
标签: arrays typescript collections
与在 JavaScript 中的方式相同。
delete myArray[key];
请注意,这会将元素设置为undefined。
最好使用Array.prototype.splice函数:
const index = myArray.indexOf(key, 0);
if (index > -1) {
myArray.splice(index, 1);
}
【讨论】:
var index: number = myArray.indexOf(key, 0);
indexOf 返回一个number?
index,并且其中一个地方 (splice) 想要查看一个数字,否则您会收到错误消息。目前编译器无法防止你在那里犯错。
var index = myArray.findIndex(x => x.prop==key.prop);。
delete myArr[2] 从字面上删除了myArr 的属性 2,这也与myArr[2] = undefined 不同。这个故事的寓意是只使用splice 来完成这项任务,因为它是一种安全的方法,可以在不混淆副作用的情况下获得所需的效果。
如果数组是对象类型,那么最简单的方法是
let foo_object // Item to remove
this.foo_objects = this.foo_objects.filter(obj => obj !== foo_object);
【讨论】:
this.foo_objects = this.foo_objects.filter(obj => obj !== foo_object)[0];
在 ES6 中,您可以使用以下代码:
removeDocument(doc){
this.documents.forEach( (item, index) => {
if(item === doc) this.documents.splice(index,1);
});
}
【讨论】:
这是我的解决方案:
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"]
【讨论】:
pop 方法而不是splice。
让部门是一个数组。你想从这个数组中删除一个项目。
departments: string[] = [];
removeDepartment(name: string): void {
this.departments = this.departments.filter(item => item != name);
}
【讨论】:
这是一个简单的单行代码,用于从对象数组中按属性删除对象。
delete this.items[this.items.findIndex(item => item.item_id == item_id)];
或
this.items = this.items.filter(item => item.item_id !== item.item_id);
【讨论】:
这对我有用。
你的数组:
DummyArray: any = [
{ "id": 1, "name": 'A' },
{ "id": 2, "name": 'B' },
{ "id": 3, "name": 'C' },
{ "id": 4, "name": 'D' }
]
功能:
remove() {
this.DummyArray = this.DummyArray.filter(item => item !== item);
}
注意:此函数会删除数组中的所有对象。如果要从数组中删除特定对象,请使用此方法:
remove(id) {
this.DummyArray = this.DummyArray.filter(item => item.id !== id);
}
【讨论】:
如果您需要从数组中删除给定的对象,并且您希望确保以下几点,请使用此选项:
const objWithIdToRemove;
const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
if (objIndex > -1) {
this.objectsArray.splice(objIndex, 1);
}
【讨论】:
const 而不是let。
使用 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;
【讨论】:
另一个使用 Typescript 的解决方案:
let updatedArray = [];
for (let el of this.oldArray) {
if (el !== elementToRemove) {
updated.push(el);
}
}
this.oldArray = updated;
【讨论】:
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/Javascript 中的多个选项可从数组中删除元素。 拼接是最好的选择
以下是使用 Splice 函数根据对象数组中的某些字段删除对象的示例
const persons = [
{
firstName :'John',
lastName :'Michel'
},
{
firstName :'William',
lastName :'Scott'
},
{
firstName :'Amanda',
lastName :'Tailor'
}
]
console.log('Before Deleting :'+JSON.stringify(persons));
console.log('Deleting William:');
persons.splice(persons.findIndex(item => item.firstName === 'William'),1);
console.log('After Deleting William'+JSON.stringify(persons));
【讨论】:
只是想为数组添加扩展方法。
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;
};
【讨论】:
您可以尝试先获取列表或数组的索引或位置,然后使用 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]);
}
}
【讨论】:
我们可以使用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' ]
【讨论】:
我看到很多抱怨remove 方法不是内置的。考虑使用 Set 而不是数组 - 它内置了 add 和 delete 方法。
【讨论】:
类似于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;
});
}
【讨论】: