5

Is it possible to remove something from an array using foreach?

var array = [1,2,3,4,5,6,7,8];

array.forEach(function(data){
    if (data == 4) {
        // do something here
    }
});

console.log(array);
2
  • 2
    Why would you? Use filter!!! Commented Jun 4, 2015 at 18:41
  • You have a point there. Commented Jun 4, 2015 at 19:17

3 Answers 3

4

I would advise against using the forEach function. It affects the iterator and skips the next item. Better: use a reverse for loop and remove the item by index.

var array = [1,2,3,4,5,6,7,8];

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

Fiddle: https://jsfiddle.net/uu94y8Lx/

Sign up to request clarification or add additional context in comments.

Comments

2

I would not recommend this. The forEach function iterates over the array and when you remove the current or a previous item it will skip the next item in the array. That being said if you really want to remove an item despite the problems you will run into it is possible to remove an item with array.splice(data, 1).

Comments

2

Try like this:

array.forEach(function(data){
   if (data == 4){
      console.log('done')
      array.splice(data, 1);
   }
});

Also as commented by mario its not recommended to modify the array you're looping on, so you can do like this:

var array1 = [];
array.forEach(function(data){
    if(array.length === 4){
        array1.push(data);
    }
});

Also you can use the for loop like this:

var array = [1,2,3,4,5,6,7,8],i;

for (i = 0; i < array.length; ++i) {
    if (array[i] === 4) {
        array.splice(i--, 1);
    }
}

console.log(array);

1 Comment

This does not work. See fiddle: jsfiddle.net/txzabe48 removing items during foreach affects the iterator. I recommend doing a reverse for loop and remove by index.