Search code examples
javascriptarrayssplice

Array.prototype.splice with negative indexes and delete count greater than 1 not working


Let's say we have an array like var x = [1,2,3,4,5,6] and we need to remove the last two items. While there could be many ways of doing this, I tried using this approach:

x.splice(-1, 2)

ideally, as I understand this should remove last two elements. But it doesn't instead it removes only one value.

Can anyone please explain what went wrong?


Solution

  • to remove last 2 items you should use x.splice(-2) First parameter is start point and second (not necessary - default is to the end of array) is the number of elements to remove. You should read documentation