Using splice in an enhanced for loop

Is there an issue with splice not working properly when running an enhanced for loop? this is my code.

	for (p of pieces) {
		for (other of pieces) {
			if (p != other && p.col != other.col && p.capture(other)) {
				console.log("This should be working");
				pieces.splice(other,1);
			}
		}
	}

When the if statement returns true and the splice function happens if for example other was 8 it will remove 8 indices instead of index 8. I would expect that 1 index would be removed and its the 8th index. However instead 8 indices are removed and it’s indices 0-7.

1 Like

There are a couple of issues from your posted code: :face_with_head_bandage:

The 1st parameter of method Array::splice() is the start index value:

However, you’re passing element other; which of course, isn’t an index value:
pieces.splice(other, 1);

And although minor, you need to declare variables w/ keywords var, let or const.

It doesn’t seem like your variables p & other got declared?

And a major 1: When doing any operation which can change the length of an Array, we can’t use “enhanced” loops, but stick w/ a vanilla for ( ; ; ); preferably iterating in backwards direction.

Here’s my attempt on it below. But you’ve gotta heavy test it, b/c I did NONE: :sleeping:

for (let j, i = pieces.length; i--;) {
  const p = pieces[j = i];

  while (j--)  if (p.capture(pieces[j])) {
    pieces[j] = pieces.pop();
    break;
  }
}
1 Like