Thu Oct 07 2021·2 min read
Photo by Matteo Vistocco
To remove the last
n elements from an array, call the
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
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
0and the last element an index of
arr.length - 1.
In our example we have a start index of
1, meaning we start removing elements
1, and we remove
splice method changes the contents of the original array.
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.
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:
-3means extract up to, but not including the last
3elements of the array
arr.length - 3is the same. We instruct the
slicemethod to copy up to, but not including the last
3elements 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.