How to Remove an Element from an Array in TypeScript

To remove an element from an array in TypeScript, you can use the “array.splice()” or “array.filter()” method.

Method 1: Using the array.splice() function

The array.splice() method modifies the original array by removing or replacing elements. It takes two arguments: the start index and the number of elements to delete.

Example

const arr = [1, 2, 3, 4, 5];
const indexToRemove = 2;

if (indexToRemove > -1) {
  arr.splice(indexToRemove, 1);
}

console.log(arr);

Output

[ 1, 2, 4, 5 ]

Method 2: Using the array.filter() function

The array.filter() method creates a new array with all the elements that pass a specified test implemented by a provided function. In this case, the test is whether the element’s index differs from the one you want to remove.

Example

const arr = [1, 2, 3, 4, 5];
const indexToRemove = 2;

const newArr = arr.filter((_, index) => index !== indexToRemove);

console.log(newArr);

Output

[ 1, 2, 4, 5 ]

Both methods share the same runtime behavior. However, the splice() method modifies the original array, while the filter() method creates a new array without the removed element.

Choose the method that best suits your use case and coding style.

Leave a Comment