Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!