remove an element from the beginning of an array in typescript

You can remove the first element of an array in TypeScript using the shift() method, which mutates the original array. The shift() method returns the element that was removed, or undefined if the array is empty.

index.ts
const myArray = [1, 2, 3];

const shiftedElement = myArray.shift();

console.log(myArray); // Output: [2, 3]
console.log(shiftedElement); // Output: 1
151 chars
7 lines

If you don't want to mutate the original array, you can use the slice() method to create a new array with all elements except the first one.

index.ts
const myArray = [1, 2, 3];

const newArray = myArray.slice(1);

console.log(myArray); // Output: [1, 2, 3]
console.log(newArray); // Output: [2, 3]
148 chars
7 lines

Another way to remove the first element of an array is to use the splice() method. The splice() method can remove one or more elements from an array and returns the removed elements as a new array.

index.ts
const myArray = [1, 2, 3];

const removedElements = myArray.splice(0, 1);

console.log(myArray); // Output: [2, 3]
console.log(removedElements); // Output: [1]
160 chars
7 lines

In this example, the splice() method removes the first element from the array (0 index) and removes 1 element. The removed element is returned in the removedElements array.

gistlibby LogSnag