Removing a last item from the JavaScript array is something that we’ve to do sometimes with our code.
In this article, we’ll look at how to remove the last item from a JavaScript array.
Array.prototype.splice
We can use the JavaScript array’s splice
method to remove the last item from the array.
For instance, we can write:
const array = [1, 2, 3]
array.splice(-1, 1)
console.log(array)
We call splice
with -1 to remove the last item from the array.
And 1 specifies that remove one item.
Then array
is [1, 2]
.
Array.prototype.pop
We can call the pop
method to remove the last item from the array.
It returns the item that’s been removed.
To use it, we can write:
const array = [1, 2, 3]
const popped = array.pop()
console.log(popped, array)
We call pop
on array
to remove the last item from array
.
And we assigned the removed item to popped
.
So popped
is 3.
And array
is [1, 2]
.
Array.prototype.slice
Another array method we can use to remove the last item from an array is the slice
method.
It returns an array with the start and end index.
For instance, we can write:
const array = [1, 2, 3]
const newArr = array.slice(0, -1);
console.log(newArr)
We call slice
with the start and end index to return an array from the start index to the end index.
The item at the end index isn’t included, but the one in the start is included.
The number -1 means the index of the last item in the array.
Therefore, we get:
[1, 2]
as the value of newArr
.
Array.prototype.filter
We can use the array filter
method to return an array with items that meet the given condition.
Therefore, we can check if the item is in the last index of the array.
For instance, we can write:
const array = [1, 2, 3]
const newArr = array.filter((element, index) => index < array.length - 1);
console.log(newArr)
We pass in a callback to the filter
method that returns index < array.length — 1
to return all the items with index less than array.length — 1
.
Therefore, we’ll get the same result for newArr
as the previous example.
Conclusion
We can use JavaScript array methods to remove the last item from an array.