# Using splice in an enhanced for loop

**URL:** <https://discourse.processing.org/t/using-splice-in-an-enhanced-for-loop/11931>\
**Category:** Coding Questions\
**Created:** [June 8, 2019, 7:05pm UTC](https://discourse.processing.org/t/using-splice-in-an-enhanced-for-loop/11931 "2019-06-08T19:05:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ZachMcMkay](https://avatars.discourse-cdn.com/v4/letter/z/8e7dd6/32.png) [@ZachMcMkay](https://discourse.processing.org/u/ZachMcMkay)\
**Post date:** [June 8, 2019, 7:05pm UTC](https://discourse.processing.org/t/using-splice-in-an-enhanced-for-loop/11931/1 "2019-06-08T19:05:09Z")

</div>

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

```auto
	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.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [June 8, 2019, 8:26pm UTC](https://discourse.processing.org/t/using-splice-in-an-enhanced-for-loop/11931/2 "2019-06-08T20:26:20Z")

</div>

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

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

> **[Array.prototype.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Syntax)**
>
> The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

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: 😴

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

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

```
