EN
TypeScript - remove element from array by index
0 points
In TypeScript, it is not intuitive at the first time how to remove element by index. Remove the element by index operation can be achieved with Array.prototype.splice
method. This article is focused on how to do it.
Quick solution:
xxxxxxxxxx
1
array.splice(index, 1); // removes 1 element
Where:
array
- from this array we want to remove an element,index
- removed element index,1
- means the amount of the removed elements - we remove 1 element.
xxxxxxxxxx
1
// index: 0 1 2 3
2
const array: string[] = ['a', 'b', 'c', 'd'];
3
4
// removes 3rd element
5
const removedElements: string[] = array.splice(2, 1); // removed from index: 2, removed elements amount: 1
6
7
console.log(array);
8
console.log(removedElements);
Output:
xxxxxxxxxx
1
['a', 'b', 'd']
2
['c']
Array.prototype.splice(index, count)
method:
- takes:
index
- starting from this index elements will be removed,count
- number of the elemnts to remove starting from index,- returns:
- array with removed elements
- warning:
splice()
method middifies array
xxxxxxxxxx
1
const removeItem = (array: string[], index: number): string => {
2
const items: string[] = array.splice(index, 1);
3
if (items.length > 0) {
4
return items[0];
5
}
6
return null;
7
};
8
9
// Usage example:
10
11
// index: 0 1 2 3
12
const array: string[] = ['a', 'b', 'c', 'd'];
13
14
const removedItem: string = removeItem(array, 2);
15
16
console.log(array);
17
console.log(removedItem);
Output:
xxxxxxxxxx
1
['a', 'b', 'd']