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

141
Views
How to get the first item from an JavaScript iterator that satisfies a testing function

I have an iterator object, and I would like to get the first element that satisfies a testing function.

I know I can use Array.prototype.find if I convert the iterator to an array. using the [...ducks].find((duck) => duck.age >= 3) syntax for example.

But I do not want to convert the iterator to an array because it's wasteful. In my example, I have many ducks, and I need an old one that will be found after only a few tests.

I'm wondering whether an elegant solution exists.

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

0

There's nothing built in, but you can readily write a function for it, stick it in your utilities toolkit, and reuse it:

function find(it, callback) {
    for (const value of it) {
        if (callback(value)) {
            return value;
        }
    }
}

Usage:

const duck = find(ducks, (duck) => duck.age >= 3);
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!