Remove first element from an array in JavaScript
This post will discuss how to remove the first element from an array in JavaScript.
1. Using Array.prototype.shift() function
The standard method to remove the first element from an array is using shift() method. The following example demonstrates the usage of the shift() to in-place remove the first element from the array.
|
1 2 3 4 5 6 7 8 |
let arr = [ 2, 4, 3, 6, 8 ]; let first = arr.shift(); console.log(arr); /* Output: [ 4, 3, 6, 8 ] */ |
2. Using Array.prototype.splice() function
The splice() method is frequently used to remove existing elements from the array.
The following code creates an array containing five elements, then calls the slice() method to create a shallow copy of all the original array values except the first.
|
1 2 3 4 5 6 7 8 |
let arr = [ 2, 4, 3, 6, 8 ]; arr = arr.splice(1); console.log(arr); /* Output: [ 4, 3, 6, 8 ] */ |
You can easily extend the above code to return everything but the first n elements from the array.
|
1 2 3 4 5 6 7 8 9 |
let arr = [ 2, 4, 3, 6, 8 ]; let n = 3; arr = arr.splice(n); console.log(arr); /* Output: [ 6, 8 ] */ |
3. Using Lodash Library
If you’re using the Lodash JavaScript library in your project, you can use the tail() method, which will return everything but the first element of the array. Note that this doesn’t modify the original array but returns a new array.
|
1 2 3 4 5 6 7 8 9 10 |
let _ = require('lodash'); let arr = [ 2, 4, 3, 6, 8 ]; arr = _.tail(arr); console.log(arr); /* Output: [ 4, 3, 6, 8 ] */ |
4. Using Underscore Library
Alternatively, using the Underscore JavaScript library, you can use the rest() method to get a copy of the array with the first element removed.
|
1 2 3 4 5 6 7 8 9 10 |
let _ = require('underscore'); let arr = [ 2, 4, 3, 6, 8 ]; arr = _.rest(arr); console.log(arr); /* Output: [ 4, 3, 6, 8 ] */ |
To remove the first n elements from the array, you can pass the total number of elements to the function.
|
1 2 3 4 5 6 7 8 9 10 11 |
let _ = require('underscore'); let arr = [ 2, 4, 3, 6, 8 ]; let n = 3; arr = _.rest(arr, n); console.log(arr); /* Output: [ 6, 8 ] */ |
That’s all about removing the first element from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)