Remove last element from an array in JavaScript
This post will discuss how to remove the last element from an array in JavaScript.
1. Using Array.prototype.pop() function
The standard way to remove the last element from an array is with the pop() method. This method works by modifying the original array. The following code creates an array containing five elements, then removes its last element.
|
1 2 3 4 5 6 7 8 |
var arr = [1, 2, 3, 4, 5]; var last = arr.pop(); console.log(arr); /* Output: [ 1, 2, 3, 4 ] */ |
2. Using Array.prototype.splice() function
The splice() method is often used to in-place remove existing elements from the array or add new elements to it. The following example demonstrates the usage of the splice() to remove the last element from the array of length 5.
|
1 2 3 4 5 6 7 8 |
var arr = [1, 2, 3, 4, 5]; arr.splice(arr.length - 1); console.log(arr); /* Output: [ 1, 2, 3, 4 ] */ |
You can easily extend the above code to remove the last n elements from the array:
|
1 2 3 4 5 6 7 8 9 |
var arr = [1, 2, 3, 4, 5]; var n = 3; arr.splice(arr.length - n); console.log(arr); /* Output: [ 1, 2 ] */ |
3. Using Lodash Library
If you’re using the Lodash JavaScript library in your project, you can use the initial() method, which returns everything but the last 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 |
var _ = require('lodash'); var arr = [1, 2, 3, 4, 5]; arr = _.initial(arr); console.log(arr); /* Output: [ 1, 2, 3, 4 ] */ |
4. Using Underscore Library
Alternatively, to remove the last n elements from the array, pass n as the second parameter to initial() method of Underscore library.
|
1 2 3 4 5 6 7 8 9 10 11 |
var _ = require('underscore'); var arr = [1, 2, 3, 4, 5]; var n = 3; arr = _.initial(arr, n); console.log(arr); /* Output: [ 1, 2 ] */ |
That’s all about removing the last 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 :)