Short answer: use a reverse loop if manipulating the array within the loop:
var i = d.rewrites.length;
while (i--) {
if (blah) {
d.rewrites.splice(i, 1)
}
}
Long answer:
Manipulating an array within a forEach causes the same problems splicing an array within a forward loop cause, all elements following the index of the splice shift one position to the left:
var arr = [3,4,5,6,7]
for (var i = 0, len = arr.length; i < len; ++i) {
console.log(i);
arr.splice(i, 1);
}
After this, arr holds [4,6]. Breaking it down a bit:
var arr = [3,4,5,6,7]
arr.splice(0, 1) // arr is [4,5,6,7]
arr.splice(1, 1) // arr is [4,6,7]
arr.splice(2, 1) // arr is [4,6]
arr.splice(3, 1) // no change
arr.splice(4, 1) // no change
Not the intention. Instead, start the index from the end and iterate to the beginning and it will behave as desired.
var arr = [3,4,5,6,7]
arr.splice(4, 1) // arr is [3,4,5,6]
arr.splice(3, 1) // arr is [3,4,5]
arr.splice(2, 1) // arr is [3,4]
arr.splice(1, 1) // [3]
arr.splice(0, 1) // []