Remove first n elements of an array
How to solve it
Approach 1
The most recommended and easy way to remove certain elements from an array is to use the slice method.
The slice operator takes two optional parameters (start, end). You can use these parameters to define a range of elements that you want to keep from the original array. Consider the following array:
const arr = [0,1,2,3,4];
If we would want to have a new array that only has the third and the fourth element of arr, we would call:
arr.slice(2,4);
// output: [2,3]
Our start parameter is 2 because this is the index of the third element - the first element that we want to include in the output. The end parameter is 4 because this is the index of the fifth element - the first element that we do not wish to be included in the outcome.
This method can be applied to our problem. If we want to remove some elements from the beginning of an array, then we only have to define the start parameter.
arr.slice(2);
// output: [2,3,4]
I recommend this approach because it leaves the original array untouched and creates a new one instead. This is a good way to avoid bugs in your code.
const arr = [0,1,2,3,4]; console.log(arr.slice(2)); // output: [2,3,4] // the original array did not change: console.log(arr); // output: [0,1,2,3,4]
Approach 2
Another way to remove the first n elements from an array is to use the splice method.
It is used to remove or replace elements of an array (or even add new elements). It takes as first parameter the start index for your operation. The second (optional) parameter defines how many items you want to delete. Further (optional) parameters define the items you want to add to the array.
Consider the following array:
const arr = [0,1,2,3,4];
To remove the first 2 elements from the array, we call:
arr.splice(0,2);
The start parameter is 0 because we want to remove elements from the beginning of the array. The second parameter is 2 because we want to delete 2 elements.
It is important to consider that this method mutates the original array.
const arr = [0,1,2,3,4]; console.log(arr.splice(0,2)); // output: [0,1] // the original array changed: console.log(arr); // output: [2,3,4]