Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda