Skip to main content

filter

filter() function

Return Iterable/AsyncIterable of all elements f returns truthy for

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

declare function filter<A, B extends A>(f: (a: A) => a is B, iterable: Iterable<A>): IterableIterator<B>;

declare function filter<A>(f: BooleanConstructor, iterable: Iterable<A>): IterableIterator<TruthyTypesOf<A>>;

declare function filter<A, B = unknown>(f: (a: A) => B, iterable: AsyncIterable<A>): AsyncIterableIterator<A>;

declare function filter<A, B extends A>(f: (a: A) => a is B, iterable: AsyncIterable<A>): AsyncIterableIterator<B>;

declare function filter<A>(f: BooleanConstructor, iterable: AsyncIterable<A>): AsyncIterableIterator<TruthyTypesOf<A>>;

declare function filter<A extends Iterable<unknown> | AsyncIterable<unknown>>(f: BooleanConstructor): (iterable: A) => ReturnIterableIteratorType<A, TruthyTypesOf<IterableInfer<A>>>;

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

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

Example

const iter = filter((a)=> a % 2 === 0, [0, 1, 2, 3, 4, 5, 6]);
iter.next() // {done:false, value: 0}
iter.next() // {done:false, value: 2}
iter.next() // {done:false, value: 4}
iter.next() // {done:false, value: 6}
iter.next() // {done:true, value: undefined}

// with pipe
pipe(
[0, 1, 2, 3, 4, 5, 6],
filter(a => a % 2 === 0),
toArray,
); // [0, 2, 4, 6]

await pipe(
Promise.resolve([0, 1, 2, 3, 4, 5, 6]),
filter(a => a % 2 === 0),
toArray,
); // [0, 2, 4, 6]

// if you want to use asynchronous callback
await pipe(
Promise.resolve([0, 1, 2, 3, 4, 5, 6]),
toAsync,
filter(async a => a % 2 === 0),
toArray,
); // [0, 2, 4, 6]

// toAsync
await pipe(
[Promise.resolve(0), Promise.resolve(1), Promise.resolve(2), Promise.resolve(3),
Promise.resolve(4), Promise.resolve(5), Promise.resolve(6)],
toAsync,
filter(a => a % 2 === 0),
toArray,
); // [0, 2, 4, 6]

Try It

see pipe, toAsync, toArray