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.
1. Insert elements starting fromĀ some index positionĀ withĀ Array.prototype.splice method example
// ONLINE-RUNNER:browser;
// index: 0 1 2 3
const array: string[] = ['a', 'b', 'c', 'd'];
// inserting into 1st index position, 1 element, 'new item' element
array.splice(1, 0, 'new item 1', 'new item 2', 'new item 3', 'new item N');
console.log(array);
Output:
[
'a',
'new item 1',
'new item 2',
'new item 3',
'new item N',
'b',
'c',
'd'
]
Notes about
Array.prototype.splicemethod:
- 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