JS: Iterator.prototype.flatMap

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2025)

iterator.flatMap(f)

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

  • f is given args:
  • currentElement
  • currentIndex
// define a generator function
function* gf() {
  for (let x of [1, 2, 3, 4, 5, 6]) yield x;
}

// if number is even, repeat it, else delete it
const xx = gf().flatMap((x) => ((x % 2 === 0) ? [x, x] : []));

console.log(JSON.stringify(Array.from(xx)) === `[2,2,4,4,6,6]`);
// true

// is iterable
console.log(Reflect.has(xx, Symbol.iterator));
// true

// is iterator
console.log(Reflect.has(xx, "next"));
// true

JavaScript. iterator helpers