Skip to main content

Function: flatMap()

flatMap<ElementType, MappedType>(iterable: IterableResolvable<ElementType>, callbackFn: (element: ElementType, index: number) => IterableResolvable<MappedType>): IterableIterator<MappedType>

Defined in: projects/utilities/packages/iterator-utilities/src/lib/flatMap.ts:21

Creates an iterable that yields the elements of each iterable returned by the provided function on each element of the input iterable.

Type Parameters​

Type Parameter
ElementType
MappedType

Parameters​

ParameterTypeDescription
iterableIterableResolvable<ElementType>An iterator to map.
callbackFn(element: ElementType, index: number) => IterableResolvable<MappedType>A function to execute for each element produced by the iterator. It should return an iterator or iterable that yields elements to be yielded by flatMap(), or a single non-iterator/iterable value to be yielded.

Returns​

IterableIterator<MappedType>

An iterator that applies a function to each element of the input iterator and yields the results.

Example​

import { flatMap } from '@sapphire/iterator-utilities';

const iterable = [1, 2, 3];
console.log([...flatMap(iterable, (value) => [value, value * 2])]);
// Output: [1, 2, 2, 4, 3, 6]