'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.
Solution 1:[1]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.J. Crowder |
