Skip to content
Advertisement

Javascript splice last element

var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr = arr.splice(4, 1)
console.log(arr)
//[5]

I want to remove only the last element. Why does it remove every element except the last one?

Advertisement

Answer

You need to omit the assignment.

var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]

arr.splice(4, 1);
console.log(...arr); // [1, 2, 3, 4]

If you like just to delete the last one, you could take a negative index with Array#splice. This works for any other index from the end.

var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]

arr.splice(-1, 1);
console.log(...arr); // [1, 2, 3, 4]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement