Remove the Last 2 Elements from an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

Remove the Last 2 Elements from an Array #

Use the splice() method to remove the last 2 elements from an array, e.g. arr.splice(arr.length - 2, 2). The splice method will delete the 2 last elements from the array and return a new array containing the deleted elements.

index.js
// ๐Ÿ‘‡๏ธ With mutation const arr1 = ['one', 'two', 'three', 'four']; arr1.splice(arr1.length - 2, 2); console.log(arr1); // ๐Ÿ‘‰๏ธ ['one', 'two']

We used the Array.splice method to delete the last 2 elements from an array.

These are the 2 arguments we passed to the method:

  1. start index - the index at which to start changing the array
  2. delete count - how many elements we want to delete from the array
Indexes are zero-based in JavaScript, meaning the first element in an array has an index of 0, and the last an index of array.length - 1.

We used the array's length to calculate the start index. Our array has a length of 4, so by subtracting 2 from it, the splice method starts changing the array at index 2 (the third array element).

We removed 2 items, by setting the delete count parameter to 2.

Note that the splice method changes the contents of the original array. If you want to get a new array without the last 2 elements of the original array, you can use the slice method instead.

To remove the last 2 elements from an array, call the slice() method, passing it 0 and -2 as parameters. The slice method will return a new array containing the portion of the original array, without the last 2 elements.

index.js
// ๐Ÿ‘‡๏ธ Without mutations const arr2 = ['one', 'two', 'three', 'four']; const newArr = arr2.slice(0, -2); console.log(newArr); // ๐Ÿ‘‰๏ธ ['one', 'two'] console.log(arr2); // ๐Ÿ‘‰๏ธ ['one', 'two', 'three', 'four']

We passed the following parameters to the Array.slice method:

  1. start index - the index of the first element to be included in the new array
  2. end index - extract elements up to, but not including this index. A negative index of -2 means go up to, but not including the last 2 elements of the array
Passing an end index parameter of -2 and array.length - 2 is the same. We instruct the slice method to go up to, but not including the last 2 elements in the array.

The slice method does not mutate the original array, instead it returns a new array.

Using the slice method is my preferred approach, because in my experience, mutations are very difficult to track throughout a code base, especially when changing the same array / object in different places.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee