Last updated: Jul 25, 2022
Photo from Unsplash
To remove the first n elements from an array:
splice method on the array, passing it the start index and the
number of elements to remove as arguments.
arr.splice(0,2) removes the first two elements from the array
and returns a new array containing the removed elements.
const arr = ['a', 'b', 'c', 'd']; const removeFirstTwo = arr.splice(0, 2); console.log(removeFirstTwo); // 👉️ ['a', 'b'] console.log(arr); // 👉️ ['c', 'd']
We passed the following 2 arguments to the Array.splice method:
We supplied a start index of
0 and a delete count of
2 to remove the first 2
elements from the array.
Array.splice method removes the elements from the original array and
returns them in a new array.
All of the elements from the start index onwards will be deleted, if:
const arr = ['a', 'b', 'c', 'd']; const removeAll = arr.splice(0); console.log(removeAll); // 👉️ ['a', 'b', 'c', 'd'] console.log(arr); // 👉️ 
We omitted the delete count parameter, which means that all elements from the specified start index onwards will get removed from the array.
We can use the Array.slice method to create a copy of the original array, containing only the elements we need.
const arr = ['a', 'b', 'c', 'd']; const newArr = arr.slice(1, 3); console.log(newArr); // 👉️ ['c', 'd'] console.log(arr) // 👉️ ['a', 'b', 'c', 'd']
Note that the
Array.slice method doesn't remove the elements from the original
We passed the following parameters to the
In the code snippet, we start extracting values at index
1 go up to, but not
Creating a copy of the original array, which contains only the elements we need is a better approach than mutating the array.
Mutations are very difficult to reason about and track throughout a codebase.