Removing array elements while iterating through the elements in a loop can be tricky for a beginner.
Consider this -
|
|
This looks like a lazy weekend programming puzzle, but also goes to demonstrate what can happen if the loop is not understood well.
The above code does not delete all elements but removes alternate elements.
|
|
In the for
loop splice removes one element each time. When we step through time -
Iteration | nums | Index (i) postn. | Element at nums[i] | Array after delete |
---|---|---|---|---|
1 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | 0 | 1 | [2, 3, 4, 5, 6, 7, 8, 9, 10] |
2 | [2, 3, 4, 5, 6, 7, 8, 9, 10] | 1 | 3 | [2, 4, 5, 6, 7, 8, 9, 10] |
3 | [2, 4, 5, 6, 7, 8, 9, 10] | 2 | 5 | [2, 4, 6, 7, 8, 9, 10] |
4 | [2, 4, 6, 7, 8, 9, 10] | 3 | 7 | [2, 4, 6, 8, 9, 10] |
5 | [2, 4, 6, 8, 9, 10] | 4 | 9 | [2, 4, 6, 8, 10] |
As you see, we processed the array in half as many steps as we anticipated at the beginning. This is because each time the array shrank with splice
but i
continued to increment and delete the element at i
th position. So, every alternate elements got deleted.
Avoiding the problem is easy. You just increment your own counter, or go reverse while iterating the array.
|
|