Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 485
e741af0d41bc74bf854041f1fbdbf Avatar asked Dec 02 '25 22:12

e741af0d41bc74bf854041f1fbdbf


1 Answers

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);
like image 172
T.J. Crowder Avatar answered Dec 04 '25 14:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!