Kristen Hare
Kristen Hare

Reputation: 21

Is it possible to splice an item from an array using a 'for of' loop in javascript?

I've been able to figure out splicing using a 'for' loop and a 'for in' loop, but not a 'for of' loop. Is it possible? Here's my starting code... any ideas what I can change to make it work?

let array = [ 'a', 'b', 'c' ];
function remove( letter ){
    for( let item of array ){
        if( item === letter ){
            parkedCars.splice ( item, 1 );
        }
    }
}
remove( 'b' );
console.log( array );

Upvotes: 2

Views: 773

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122047

You could use for...of loop on Array.prototype.entries() and then check value and remove item by index using splice().

let array = ['a', 'b', 'c'];

function remove(arr, letter) {
  for (let [index, item] of arr.entries()) {
    if (item === letter) arr.splice(index, 1);
  }
}
remove(array, 'b');
console.log(array);

Upvotes: 5

brunnerh
brunnerh

Reputation: 184607

Well, you can track the index yourself, it's not very pretty though.

let index = 0;
for( let item of array ){
    if( item === letter ){
        parkedCars.splice ( index, 1 );
    }
    index++;
}

Upvotes: 0

Related Questions