0

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?

7
  • Wouldn't it be better to create a new array and assign it? Mutation, especially in this case could result in some unforseen side effects, no? I don't tried it, but just mentioning Commented Sep 22, 2021 at 11:04
  • The index gets wrong if you start removing items in an array while looping, but you could start looping from the end with a normal for(let i = data.length-1...). Commented Sep 22, 2021 at 11:04
  • @LingVu I'm not very skilled in js, but yes, I was afraid that mutation would be an issue. And I want to change the code as little as possible. Commented Sep 22, 2021 at 11:05
  • Why not a filter? data2 = data.filter( x => getValue(x) > 5) or something Commented Sep 22, 2021 at 11:09
  • 1
    That's another XY problem (many problems posted here are). You want to filter an array (problem X), but you don't know how to do that, so you try to make a for loop in which you want to remove elements (problem Y), but you don't know how to do that either, so you ask help about what you believe will solve your original problem (Y), instead of the original problem itself (X). Commented Sep 22, 2021 at 11:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I'll use that then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.