Skip to main content

flatMap

flatMap() function

Returns flattened Iterable/AsyncIterable of values by running each element flattening the mapped results.

Signature:
declare function flatMap<A, B = unknown>(f: (a: A) => B, iterable: Iterable<A>): IterableIterator<DeepFlatSync<B, 1>>;

declare function flatMap<A, B = unknown>(f: (a: A) => B, iterable: AsyncIterable<A>): AsyncIterableIterator<DeepFlat<Awaited<B>, 1>>;

declare function flatMap<A extends Iterable<unknown> | AsyncIterable<unknown>, B = unknown>(f: (a: IterableInfer<A>) => B): (iterable: A) => ReturnFlatMapType<A, B>;

declare function flatMap<A extends Iterable<unknown> | AsyncIterable<unknown>, B = unknown>(f: (a: IterableInfer<A>) => B, iterable?: A): (iterable: A) => ReturnFlatMapType<A, B>;

Example

const iter = flatMap(s => s.split(" "), ["It is", "a good", "day"]);
iter.next() // {done:false, value: "It"}
iter.next() // {done:false, value: "is"}
iter.next() // {done:false, value: "a"}
iter.next() // {done:false, value: "good"},
iter.next() // {done:false, value: "day"},
iter.next() // {done:true, value: undefined}

// with pipe
pipe(
["It is", "a good", "day"],
flatMap(s => s.split(" ")),
toArray,
); // ["It", "is", "a", "good", "day"]

await pipe(
Promise.resolve(["It is", "a good", "day"]),
flatMap(s => s.split(" ")),
toArray,
); // ["It", "is", "a", "good", "day"]

// if you want to use asynchronous callback
await pipe(
Promise.resolve(["It is", "a good", "day"]),
toAsync,
flatMap(async (s) => s.split(" ")),
toArray,
); // ["It", "is", "a", "good", "day"]

Try It

see pipe, toAsync, toArray

Open Source Code