Logo

How do I remove an array item in TypeScript?

In TypeScript, removing an item from an array typically involves methods like splice(), filter(), or slice(). Since TypeScript is a superset of JavaScript, you can use standard JavaScript array techniques, while gaining the benefit of type checks if your array is strongly typed.

1. Using splice(index, 1)

If you know the index of the item to remove, you can use splice, which mutates the array in-place.

const numbers: number[] = [10, 20, 30, 40, 50]; const removeIndex = 2; // remove the item at index 2 (which is 30) numbers.splice(removeIndex, 1); console.log(numbers); // [10, 20, 40, 50]
  • splice(start, deleteCount) removes deleteCount items starting from position start.
  • This modifies the existing array.

2. Using filter() for an Immutable Approach

If you want to produce a new array without modifying the original:

const numbers: number[] = [10, 20, 30, 40]; const itemToRemove = 30; // remove item '30' const newNumbers = numbers.filter(num => num !== itemToRemove); console.log(newNumbers); // [10, 20, 40]
  • filter() returns a new array of items that satisfy the predicate.
  • This is great for functional programming or if you don’t want side effects.

3. Using slice() (Combined with findIndex or indexOf)

You can also do something like:

const items: string[] = ["a", "b", "c", "d"]; const toRemove = "c"; const index = items.indexOf(toRemove); if (index !== -1) { // create a new array without 'c' const newItems = [...items.slice(0, index), ...items.slice(index + 1)]; console.log(newItems); // ["a", "b", "d"] }
  • indexOf finds where the item is located (-1 if not found).
  • slice(0, index) takes everything before it, slice(index+1) takes everything after.
  • We combine them via the spread operator [... ].

4. Additional Tips

  1. TypeScript just enforces type checks—removal logic is the same as plain JavaScript.
  2. splice is the typical, straightforward way to remove by index and mutate the original array.
  3. filter or slice-based approaches create a new array, which can be preferable in functional or React-like patterns to avoid side effects.

If you want to master more core JavaScript concepts (which TypeScript builds upon), consider the Grokking JavaScript Fundamentals course by DesignGurus.io, which covers crucial topics like prototypes, closures, async, and more—enabling you to use advanced TypeScript features more effectively.

CONTRIBUTOR
TechGrind