EN
TypeScript - insert many elements to array
0 points
In TypeScript it is not intuitive at first time how to insert elements to array starting from some index position. The insert operation can be achieved with Array.prototype.splice
method. This article is focused on how to do it.
xxxxxxxxxx
1
// ONLINE-RUNNER:browser;
2
3
// index: 0 1 2 3
4
const array: string[] = ['a', 'b', 'c', 'd'];
5
6
// inserting into 1st index position, 1 element, 'new item' element
7
array.splice(1, 0, 'new item 1', 'new item 2', 'new item 3', 'new item N');
8
9
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
'b',
8
'c',
9
'd'
10
]
Notes about
Array.prototype.splice
method:
- takes as first argument index into 1st index position
- takes as second argument number of removed elements - in this case we do not remove elements
- takes as third and next arguments elements that will be added - number of elements is not limited