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

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


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.


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.


ForEach, since ES5 can be used together with an index:

data.forEach(function (element, index) {  if (element % 2 == 0) {    data.splice(index, 1);  }});