How to iterate over an array and remove elements in JavaScript

JavascriptIterationBounds

Javascript Problem Overview


I have an array of elements and need to remove certain ones from it. The problem is that JavaScript doesn't seem to have a for each loop and if I use a for loop I run into problems with it basically trying to check elements beyond the bounds of the array, or missing elements in the array because the indexes change. Let me show you what I mean:

var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = 0; i < elements.length; i++){
    if(elements[i] == 5){
        elements.splice(i, 1);
    }
}

The problem is that when elements[1] is removed, elements[2] becomes elements[1]. So first problem is that some elements are never examined. The other problem is that .length changes and if I hard code the bounds, then I might be trying to examine elements beyond the bounds of the array. So what's the best way to do this incredibly simple thing?

Javascript Solutions


Solution 1 - Javascript

Start from the top!

var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = elements.length -1; i >= 0 ; i--){
    if(elements[i] == 5){
        elements.splice(i, 1);
    }
}

Solution 2 - Javascript

You could use the filter method here:

var elements = [1, 5, 5, 3, 5, 2, 4].filter(function(a){return a !== 5;});
//=> elements now [1,3,2,4]

Or if you don't want to touch elements:

var elementsfiltered
   ,elements = [1, 5, 5, 3, 5, 2, 4]
                .filter( function(a){if (a!==5) this.push(a); return true;},
                         elementsfiltered = [] );
   //=> elementsfiltered = [1,3,2,4], elements = [1, 5, 5, 3, 5, 2, 4]

See MDN documentation for filter

Alternatively you can extend the Array.prototype

Array.prototype.remove = Array.prototype.remove || function(val){
    var i = this.length;
    while(i--){
        if (this[i] === val){
            this.splice(i,1);
        }
    }
};
var elements = [1, 5, 5, 3, 5, 2, 4];
elements.remove(5);
//=> elements now [1,3,2,4]

Solution 3 - Javascript

var elements = [1, 5, 5, 3, 5, 2, 4];    
var i = elements.length;
while (i--) {
    if (elements[i] == 5) {
        elements.splice(i, 1);
    }
}
console.log(elements);

Solution 4 - Javascript

You could simply decrement i whenever you remove an item.

var elements = [1, 5, 5, 3, 5, 2, 4];

var l = elements.length;
for(var i = 0; i < l; i++){
    if(elements[i] == 5){
        elements.splice(i, 1);
        i--;
    }
}

console.log(elements);

Solution 5 - Javascript

Using Array.shift():

var array = [1, 2, 3, 'a', 'b', 'c'];
while (array.length > 0) {
  console.log(array.shift());
}

Edit: Probably does not suit the specs. I misread the question (only remove certain elements) and was too eager instead to add a method that was not mentioned yet...

Solution 6 - Javascript

This is an example of using Array.indexOf, while and Array.splice to remove elements inline.

var elements = [1, 5, 5, 3, 5, 2, 4];
var remove = 5;
var index = elements.indexOf(remove);

while (index !== -1) {
    elements.splice(index, 1);
    index = elements.indexOf(remove);
}

console.log(elements);

On jsfiddle

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCaptain StackView Question on Stackoverflow
Solution 1 - JavascriptJean-Bernard PellerinView Answer on Stackoverflow
Solution 2 - JavascriptKooiIncView Answer on Stackoverflow
Solution 3 - JavascriptroubleView Answer on Stackoverflow
Solution 4 - JavascriptLachmanskiView Answer on Stackoverflow
Solution 5 - JavascriptGeertView Answer on Stackoverflow
Solution 6 - JavascriptXotic750View Answer on Stackoverflow