Remove the First 2 Elements from an Array in JavaScript


Borislav Hadzhiev

Tue Oct 26 20212 min read

Remove the First 2 Elements from an Array #

To remove the first 2 elements from an array, call the splice() method, passing it 0 and 2 as parameters, e.g. arr.splice(0, 2). The splice method will delete the first two elements from the array and return a new array containing the deleted elements.

// ๐Ÿ‘‡๏ธ with Mutation const arr = ['one', 'two', 'three', 'four']; arr.splice(0, 2); console.log(arr); // ๐Ÿ‘‰๏ธ ['three', 'four']

We used the Array.splice method to delete the first 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 removed the first 2 elements in the array 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 first 2 elements of the original array, you can use the slice method instead.

To remove the first 2 elements from an array, call the slice() method, passing it 2 as a parameter, e.g. arr.slice(2). The slice method will return a new array that contains all, but the first 2 elements from the original array.

// ๐Ÿ‘‡๏ธ without Mutation const arr = ['one', 'two', 'three', 'four']; const newArr = arr.slice(2); console.log(newArr); // ๐Ÿ‘‰๏ธ ['three', 'four'] console.log(arr); // ๐Ÿ‘‰๏ธ ['one', 'two', 'three', 'four']

The only parameter we passed to the slice method is the start index - the index of the first element that should be included in the new array.

The difference between this and the previous approach is that the slice method does not change the contents of the original 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