Languages
[Edit]
EN

TypeScript - insert many elements to array

0 points
Created by:
Mahir-Bright
1311

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.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

Alternative titles

  1. TypeScript - insert multiple items into array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join