add an element to the beginning of an array in typescript

To add an element to the beginning of an array in TypeScript, you can make use of the built-in unshift() method. This method adds one or more elements to the beginning of an array and returns the new length of the modified array.

Here's an example:

index.ts
let myArray: number[] = [2, 3, 4, 5];
myArray.unshift(1); // add 1 to the beginning of the array
console.log(myArray); // output: [1, 2, 3, 4, 5]
146 chars
4 lines

In this example, we define an array myArray with some initial values. Then, we call the unshift() method with the argument 1, which adds the value 1 to the beginning of the array. Finally, we log the modified array to the console to verify that the element was added successfully.

Note that this method modifies the original array, and returns its new length. If you want to add an element to the beginning of an array without modifying the original array, you can use the spread operator to create a new array with the additional element:

index.ts
let myArray: number[] = [2, 3, 4, 5];
let newArray: number[] = [1, ...myArray];
console.log(newArray); // output: [1, 2, 3, 4, 5]
130 chars
4 lines

In this example, we create a new array newArray by spreading the original array myArray into it using the spread operator (...). We place the new element 1 before the spread operator, so it gets added to the beginning of the new array. Finally, we log the new array to the console to verify that it contains the additional element.

gistlibby LogSnag