How do I remove an element in a list, using forEach?


Question

var people = ['alex','jason','matt'];

people.forEach(function(p){
    if(p.length > 4){
       //REMOVE THIS PERSON or pop it out of the list or whatever
    }
});

console.log(people) //should return ['alex','matt']

I want to remove an element out of the list, using this forEach loop.

1
26
8/5/2011 12:41:35 AM

Accepted Answer

You shouldn't modify the array you're looping on. You can produce a new one, though:

var newPeople = [];
people.forEach(function(p){
    if(p.length <= 4){
        newPeople.push(p);
    }
});

Why you shouldn't modify array you're looping.

30
7/16/2019 8:38:55 AM

Use the right tools for the right job. In this case:

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

or as @nnnnnn has suggested, loop backwards:

for (var i = data.length-1; i >= 0; i--) {
    if (data[i].value === 5) {
        data.splice(i, 1);
    }
}

However, you should consider using Array.prototype.filter():

data = data.filter(function (e) {
    return e.value !== 5;
});

or a utility function library such as lodash or underscore, which provide a function for removing elements from an array:

_.remove(data, function (e) {
    return e.value === 5;
});

The benefit of the latter two is that your code becomes more readable.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon