How to Remove the Last 'n' JavaScript Array Elements and Return Them?

To remove the last n number of elements from a JavaScript array and return them, you can use the Array.prototype.splice() method. It has the following syntax:

array.splice(startIndex, deleteCount)

The startIndex can be a negative value, in which case it will consider the starting point to be at that many elements from the end of the array.

For example, if you wish to remove the last three items from an array that has a total of five elements, you would use Array.prototype.splice() in the following way:

const arr = [ 1, 2, 3, 4, 5 ];
const removedElems = arr.splice(-3, 3);

console.log(removedElems); // output: [3, 4, 5]
console.log(arr); // output: [1, 2]

If startIndex is greater than the length of the array, then the startIndex will be set to the length of the array. For example:

const arr = [ 1, 2, 3 ];
const removedElems = arr.splice(-5, 2);

console.log(removedElems); // output: [1, 2]
console.log(arr); // output: [3]

If the deleteCount is greater than or equal to the length of the array, then all the elements from startIndex to the end of the array will be deleted. For example:

const arr = [ 1, 2, 3, 4, 5 ];
const removedElems = arr.splice(-3, 5);

console.log(removedElems); // output: [3, 4, 5]
console.log(arr); // output: [1, 2]

If the Array.prototype.splice() method is called on an empty array, it would return an empty array:

const arr = [];
const removedElems = arr.splice(-3, 3);

console.log(removedElems); // output: []

This is because the Array.prototype.splice() method returns an empty array when no elements are removed.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.