klutt
klutt

Reputation: 31389

How to remove element from array inside for-of loop?

I have a loop on this form in a code base I'm working on.

for(const foo of data) {
    foo.bar = getValue();
}

I want to change this, so that I remove the element foo if a condition based on foo.bar is satisfied. Is this possible within the for-of loop? Or do I need to use another approach? This is my attempt, but I don't feel secure about it. It really looks like one of those things that works until it does not.

for(const x of data) {
    foo.bar = getValue();
    if(foo.bar > 5)
        data.splice(data.indexOf(foo), 1);
}

I know that I could filter the array after creating it. Would that make more sense?

Upvotes: 0

Views: 100

Answers (1)

MikeMapanare
MikeMapanare

Reputation: 120

It makes more sense to filter the array previously to avoid mutating the array you are looping (splice mutates the array).

That way is clearer, easier to debug and you also get to avoid side effects.

Upvotes: 1

Related Questions