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:
xxxxxxxxxx
1
const removedElements: type[] = array.splice(index, 1);
2
Note:
The above code removes element with specified
index
fromarray
returning removed elements - one in our case.
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.
xxxxxxxxxx
1
// index: 0 1 2 3
2
const array: string[] = ['a', 'b', 'c', 'd'];
3
4
const elementToRemove: string = 'b';
5
const index: number = array.indexOf(elementToRemove);
6
7
if (index !== -1) {
8
const removedElements: string[] = array.splice(index, 1); // removes elementToRemove
9
10
console.log(array); // [ 'a', 'c', 'd' ]
11
console.log(removedElements); // [ 'b' ]
12
}
Output:
xxxxxxxxxx
1
[ 'a', 'c', 'd' ]
2
[ 'b' ]