HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

How do I remove an array item in TypeScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arraytypescripthowremoveitem

Problem

I have an array that I've created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?

Solution

Same way as you would in JavaScript.

delete myArray[key];


Note that this sets the element to undefined.

Better to use the Array.prototype.splice function:

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}

Code Snippets

delete myArray[key];
const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}

Context

Stack Overflow Q#15292278, score: 1134

Revisions (0)

No revisions yet.