How to remove an array item in TypeScript?
Problem:
I am working on a project using TypeScript. I have an array with a property as a key. I want to remove an item from the array. How can I do that?
In this article, we are going to learn how to remove an array item in TypeScript?
Solution 1:
ExampleArray: any = [
{ "key": 1, "item": 'faysal' },
{ "key": 2, "item": 'Islam' },
{ "key": 3, "item": 'Shuvo' },
{ "key": 4, "item": 'faysal shuvo' }
]
this is your array. This is how you remove an item from it.
removeItem(key) {
this.ExampleArray = this.ExampleArray.filter(item => item.key !== key);
}
To delete a specific object from an array you can use this method. give the key value as an argument and it will remove the item from the array.
Solution 2:
delete exampleArray[key];
by doing this the element will be set to undefined.
There is a better solution, you can use the Array.prototype.splice function:
const index = exampleArray.indexOf(key, 0);
if (index > -1) {
exampleArray.splice(index, 1);
}
Hope this solves your problem. If you have any type of problem please comment below.