Wed Oct 06 2021·2 min read
Photo by Caleb Frith
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 have passed the following 2 arguments to the Array.splice method:
In the code snippet, we have a start index of
0 and we remove
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 onward 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); // 👉️ 
In the code snippet, we have omitted the delete count parameter, which means that all elements from the specified start index onwards will get removed from the array.
To create a copy of the original array, containing only the elements we need, we can use the Array.slice method.
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 did not remove the elements from the original
array, instead it created a shallow copy with the array elements at index
We have passed the following parameters to the
In the code snippet we start extracting values at index
1 and end at index
Creating a copy of the original array, which contains only the elements we need is a better approach, than mutating the original array.
Mutations are very difficult to reason about and are more prone to bugs when refactoring code.
I'll send you 1 email a week with links to all of the articles I've written that week