Here is a great example why you should avoid mutating methods like
splice. What happens, is that
splice is cutting straight from the original array. Therefore your second
.splice happens to an already shorter array.
It would be better to use
slice. It cuts out and returns a piece of the array, but leaves the original one intact. So you can cut out another piece (using you
index variable) and it will work exactly how you expect it to.
So moral of the story – do not use methods that modify original data. Always create new state, do not mutate old state. This is also one of the basic concepts of functional programming and if you choose to follow it, you will avoid a LOT of potential errors in your programming journey.