EN
TypeScript - replace many elements in array
0 points
In TypeScript it is not intuitive at first time how to replace many elements in array. Replace operation can be achieved with Array.prototype.splice
method. This article is focused on how to do it.
xxxxxxxxxx
1
// index: 0 1 2 3 4 5 6
2
const array: string[] = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
3
4
// removing 4 elements sice 1st index position
5
// inserting sice 1st index position 4 elements
6
array.splice(1, 4, 'new item 1', 'new item 2', 'new item 3', 'new item N');
7
8
console.log(array);
Output:
xxxxxxxxxx
1
[
2
'a',
3
'new item 1',
4
'new item 2',
5
'new item 3',
6
'new item N',
7
'f',
8
'g'
9
]
Notes about
Array.prototype.splice
method:
- takes as first argument index of begining of removed elements
- takes as second argument number of removed elements
- takes as third and next arguments added elements