TIMEX
TIMEX

Reputation: 271824

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

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.

Upvotes: 34

Views: 54288

Answers (5)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

Use Array.prototype.filter instead

const filterByLength = (arr, len) => arr.filter(s => s.length <= len);

const people = ["jon", "alex", "jason", "matt"];
console.log(filterByLength(people, 4)); // ["jon", "alex", "matt"]

Upvotes: 0

Mrchief
Mrchief

Reputation: 76218

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.

Upvotes: 32

Code-Apprentice
Code-Apprentice

Reputation: 83527

You can do this very easily with filter():

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

var shortPeople = people.filter(function(p){
    return p.length <= 4);
});

console.log(people);
console.log(shortPeople);

Upvotes: 1

Gajus
Gajus

Reputation: 73828

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.

Upvotes: 62

adripanico
adripanico

Reputation: 1058

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

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

Upvotes: 0

Related Questions