Remove array item using for...of loop

According to @T.J's answer, when using a for...of loop:

If you remove the "current" entry during the iteration, you'll skip the next entry, because of the way array iterators are specified (they use the index of the entry).

This leaves two other options, using a reverse for loop and a filter function. I mentioned earlier that I need to do an operation with the current array element before deleting it.

1. Using .filter() function
and referring to @T.J's Comment

let array = [1,2,3];
let collection = [];

array = array.filter(function(entry) {
    if(entry>=2) {
        collection.push(entry);
    } 
    return entry <2;
});

console.log(collection); //returns [2,3]
console.log(array); //returns [1]

2. Using a reverse for loop

let array = [1,2,3];
let collection = [];

for(var i=array.length - 1; i>=0; i--) {
  if(array[i]>=2) {
     collection.push(array[i]);
     array.splice(i,1);
  }
}

console.log(collection); //returns [2,3]
console.log(array); //returns [1] 

The filter() function in this case requires an additional step to temporarily hold the elements that do not meet the condition. The reverse for loop offers a more cleaner way to achieve the same.


You can't reasonably use for-of for this. If you remove the "current" entry during the iteration, you'll skip the next entry, because of the way array iterators are specified (they use the index of the entry). You can see that with this contrived example:

const array = [1, 2, 3];
for (const entry of array) {
    console.log(entry);
    if (entry === 2) {
        array.splice(1, 1);
    }
}
console.log(array);

Notice how there was no loop iteration for entry 3.

I'd suggest either sticking with your reverse for loop or using filter to produce a new array containing only the entries you want to keep.

Using filter:

let array = [1, 2, 3];
array = array.filter(entry => entry < 2);
console.log(array);

I said "reasonably" above because, of course, there's always a way. You could loop through a copy of the array and maintain the index outside it:

const array = [1, 2, 3];
let index = 0;
for (const entry of [...array]) {
    if (entry >= 2) {
        array.splice(index, 1);
    } else {
        ++index;
    }
}
console.log(array);

That doesn't seem reasonable compared to the alternatives, unless of course there are constraints pushing you that way. :-)