EN
TypeScript - remove element from array by value
0
points
In this article, we would like to show you how to remove elements from an array by value in TypeScript.
Quick solution:
const removedElements: type[] = array.splice(index, 1);
Note:
The above code removes element with specified
indexfromarrayreturning removed elements - one in our case.
Practical example
In this example, we use indexOf() method to get index of the item that we want to remove. Then we use splice() method to remove the element.
// index: 0 1 2 3
const array: string[] = ['a', 'b', 'c', 'd'];
const elementToRemove: string = 'b';
const index: number = array.indexOf(elementToRemove);
if (index !== -1) {
const removedElements: string[] = array.splice(index, 1); // removes elementToRemove
console.log(array); // [ 'a', 'c', 'd' ]
console.log(removedElements); // [ 'b' ]
}
Output:
[ 'a', 'c', 'd' ]
[ 'b' ]