Remove the last N Elements from an Array in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20212 min read

Remove the last n Elements from an Array #

To remove the last n elements from an array, call the splice() method, passing it the start index and how many elements to remove as parameters. The splice method will change the contents of the original array and return the removed elements.

index.js
const arr = ['a', 'b', 'c', 'd']; const removeLast3 = arr.splice(1, 3); console.log(removeLast3); // ['b', 'c', 'd'] console.log(arr); // ๐Ÿ‘‰๏ธ ['a']

In the code snippet, we use the Array.splice method to remove the last 3 elements from the array.

We pass the following parameters to the splice method:

  1. start index - the index at which to start changing the array
  2. delete count - how many element should be removed from the start index onwards
Indexes are zero-based in JavaScript. The first element in the array has an index of 0 and the last element an index of arr.length - 1.

In our example we have a start index of 1, meaning we start removing elements at index 1, and we remove 3 elements.

The splice method changes the contents of the original array.

Most experienced developers avoid using methods that mutate objects and arrays. This behavior is difficult to debug and reason about.
Most of the time, a better approach is to create a copy of the array, containing only the elements we need.

To create a copy of the original array, which contains only the elements that we need, use the Array.slice method. This method does not change the contents of the original array.

index.js
const arr = ['a', 'b', 'c', 'd']; const withoutLast3 = arr.slice(0, -3); console.log(withoutLast3); // ๐Ÿ‘‰๏ธ ['a'] console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

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

  1. start index - the index at which we start extraction
  2. end index - extract elements up to, but not including this index. A negative index of -3 means extract up to, but not including the last 3 elements of the array
Passing an end index parameter of -3 and arr.length - 3 is the same. We instruct the slice method to copy up to, but not including the last 3 elements of the array.

The slice method does not mutate the original array, instead it just gives us a shallow copy of it, containing only the elements that we need.

Mutations are very difficult to follow throughout a code base and are avoided by most developers.

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