EN
JavaScript - remove last item from array
0 points
In this article, we would like to show you how to remove the last item from array using JavaScript.
In this example, to remove the last element from the array
we use splice()
method.
xxxxxxxxxx
1
var array = ['a', 'b', 'c'];
2
3
array.splice(-1, 1); // splice(start, deleteCount)
4
5
console.log(array); // [a,b]
Note:
array.splice(-1, 1);
is equal toarray.splice(array.length - 1, 1);
.
In this example, we use pop()
method that removes the last element from array
and returns that element.
xxxxxxxxxx
1
var array = ['a', 'b', 'c'];
2
3
array.pop();
4
5
console.log(array); // [a,b]
In this example, we use slice()
method to create a shallow copy of an array from indexStart
to indexEnd
(not included).
xxxxxxxxxx
1
var array = ['a', 'b', 'c'];
2
3
var newArray = array.slice(0, -1); // slice(indexStart, indexEnd)
4
5
console.log(newArray); // [a,b]
Warning:
This approach doesn't really remove the last element, it copies the array omitting it.