Skip to content

filter ​

The filter() function filters the elements of a generator according to a predicate. It returns a new generator containing only the elements that satisfy the condition.

Interactive example ​

Syntax ​

Classic signature with type guard ​

typescript
function filter<
	GenericElement extends unknown,
	GenericOutput extends GenericElement,
>(
	iterator: Iterable<GenericElement>,
	predicate: (item: GenericElement, params: GeneratorFilterParams) => item is GenericOutput
): Generator<GenericOutput, unknown, unknown>

Classic signature with boolean ​

typescript
function filter<
	GenericElement extends unknown,
>(
	iterator: Iterable<GenericElement>,
	predicate: (item: GenericElement, params: GeneratorFilterParams) => boolean
): Generator<GenericElement, unknown, unknown>

Curried signature ​

typescript
function filter<
	GenericElement extends unknown,
>(
	predicate: (item: GenericElement, params: GeneratorFilterParams) => boolean
): (iterator: Iterable<GenericElement>) => Generator<GenericElement, unknown, unknown>

Parameters ​

  • iterator: The generator to filter
  • predicate: Filtering function that receives:
    • item: The current element
    • params.index: The element index

Return value ​

A new Generator containing the filtered elements.

See also ​

  • asyncFilter - Asynchronous version of filter
  • map - Transforms the elements of a generator
  • reduce - Reduces a generator to a value

Sources ​

Released under the MIT license.