Borislav Hadzhiev
Wed Oct 06 2021·3 min read
Photo by Caleb Frith
To remove the first n elements from an array:
Call the splice
method on the array, passing it the start index and the
number of elements to remove as arguments.
For example, 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:
0
.In the code snippet, we have a start index of 0
and we remove 2
elements
from the array.
The 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 1
and 2
.
We have passed the following parameters to the Array.slice
method:
In the code snippet we start extracting values at index 1
and end at index
2
.
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.