Close
Close full mode
logoWebDevAssist

How to remove the last element from an array in TypeScript

How to remove the last element from an array in TypeScript:

In this post, I will show you different ways to remove the last element from an array in TypeScript. Arrays are used to store data sequentially. We need to use the index to access or modify the elements of an array. To remove the last element from an array, we have different ways. Let's try them one by one:

Method 1: Using pop() to remove the last array element in TypeScript:

pop() is an inbuilt method of array. This method removes the last element of an array and returns that element.

For example:

let givenArray = new Array(1, 2, 3, 4);
console.log('Initial array:',givenArray);
let lastElement = givenArray.pop();
console.log('Removed element:',lastElement);
console.log('Final array:',givenArray);

If you run this program, it will print the below output:

Initial array: [ 1, 2, 3, 4 ]
Removed element: 4
Final array: [ 1, 2, 3 ]

Method 2: Using slice():

slice() method can be used to get one subarray from an array. The advantage of using slice is that it will not modify the original array.

slice is defined as like below:

slice(start?: number, end?: number)

It returns a copy of one section of the array.

start and end are optional values and these are used to give the start and end index for the slicing. If start is undefined, it takes from the start element and if end is undefined it takes the end index of the array.

We can also use negative index. Negative index indicates an offset from the end. -3 indicates the third element from end.

To get the last element, we need to use -1.

let givenArray = new Array(1, 2, 3, 4);
console.log('Initial array:',givenArray);
let lastElement = givenArray.slice(-1);
console.log('Removed element:',lastElement);
console.log('Final array:',givenArray);

It will give the below output:

Initial array: [ 1, 2, 3, 4 ]
Removed element: [ 4 ]
Final array: [ 1, 2, 3, 4 ]

This will not change the original array and the return value is also an array.

Method 3: Using splice():

splice is another method to remove element from array end. It removes an element, returns it and deletes it from the array.

splice(start: number, deleteCount?: number)

start is the start index to start the delete. deleteCount is the number of elements to delete. It returns an array containing the elements deleted.

To remove the last element from an array, we have to pass -1 to splice.

let givenArray = new Array(1, 2, 3, 4);
console.log('Initial array:',givenArray);
let lastElement = givenArray.splice(-1, 1);
console.log('Removed element:',lastElement);
console.log('Final array:',givenArray);

It will remove the last element and also delete it from the array.

Initial array: [ 1, 2, 3, 4 ]
Removed element: [ 4 ]
Final array: [ 1, 2, 3 ]

Subscribe to our Newsletter

Previous
Introduction to array in TypeScript
Next
How to create an empty array in TypeScript