Items can be removed from an array using the splice method, but when doing so, all subsequent items will be shifted to a lower index. If this is done while iterating over the array, the shifting may cause the loop to skip over the element immediately after the removed element.

Determine what the loop is supposed to do:

In this example, a function is intended to remove ".." parts from a path:

However, whenever the input contain two ".." parts right after one another, only the first will be removed. For example, the string "../../secret.txt" will be mapped to "../secret.txt". After removing the element at index 0, the loop counter is incremented to 1, but the second ".." string has now been shifted down to index 0 and will therefore be skipped.

One way to avoid this is to decrement the loop counter after removing an element from the array:

Alternatively, use the filter method:

  • MDN: Array.prototype.splice().
  • MDN: Array.prototype.filter().