insert an element into an array at a specific index in typescript

One way to insert an element into an array at a specific index in TypeScript is to use the splice() method. The splice() method changes the contents of an array by removing or adding elements.

Here's an example:

index.ts
let fruits = ['apple', 'banana', 'cherry'];

fruits.splice(1, 0, 'orange');

console.log(fruits); // output: ['apple', 'orange', 'banana', 'cherry']
149 chars
6 lines

In the example above, we have an array fruits containing three elements. We then use the splice() method to insert the string 'orange' at index 1 (position 2) in the array. The first argument (1) indicates the index where the insertion should take place, the second argument (0) specifies how many elements should be removed, and the third argument ('orange') is the element to be inserted.

Note that the splice() method modifies the original array and returns an array of the removed elements (if any).

related categories

gistlibby LogSnag