JS: Iterator.prototype.filter

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2025)

iterator.filter(f)
  • Apply function f to every yield in Iterator iterator.
  • Keep only yields that f return true.
  • Return a new Generator.

Normally you can use this method on any Iterable, because all standard iterable objects are also Iterator.

  • f is given args:
  • currentElement
  • currentIndex

similar to JS: Array.prototype.filter

// define a generator function
function* gf() {
  for (let x of Array(5).keys()) yield x;
}

// create a generator
const gg = gf();

// use method filter
const hh = gg.filter((x) => (x % 2 === 0));

// convert to array
console.log(
  JSON.stringify(Array.from(hh)) === "[0,2,4]",
);
// true

JavaScript. iterator helpers