Skip to main content

reduce

reduce() function

Also known as foldl, this method boils down a list of values into a single value.

Signature:
declare function reduce<A>(f: (a: A, b: A) => A, iterable: Iterable<A>): A;

declare function reduce<A, B>(f: (a: B, b: A) => B, iterable: Iterable<A>): B;

declare function reduce<A extends readonly []>(f: Arrow, iterable: A): undefined;

declare function reduce<A extends readonly [], B>(f: Arrow, seed: B, iterable: A): B;

declare function reduce<A, B>(f: (a: B, b: A) => B, seed: B, iterable: Iterable<A>): B;

declare function reduce<A>(f: (a: A, b: A) => A, iterable: AsyncIterable<A>): Promise<A>;

declare function reduce<A, B>(f: (a: B, b: A) => B | Promise<B>, iterable: AsyncIterable<A>): Promise<B>;

declare function reduce<A, B>(f: (a: B, b: A) => B | Promise<B>, seed: B | Promise<B>, iterable: AsyncIterable<A>): Promise<B>;

declare function reduce<A extends Iterable<unknown> | AsyncIterable<unknown>, B>(f: (a: B, b: IterableInfer<A>) => B | Promise<B>): (iterable: A) => ReturnValueType<A, B>;

declare function reduce<A extends Iterable<unknown> | AsyncIterable<unknown>>(f: (a: IterableInfer<A>, b: IterableInfer<A>) => IterableInfer<A> | Promise<IterableInfer<A>>): (iterable: A) => ReturnValueType<A, IterableInfer<A>>;

Example

const sum = (a:number, b:number) => a + b;
reduce(sum, [1, 2, 3, 4]); // 10
reduce(sum, 0, [1, 2, 3, 4]); // 10

// with pipe
pipe(
[1, 2, 3, 4],
map(a => a + 10),
filter(a => a % 2 === 0),
reduce(sum),
); // 26

await pipe(
Promise.resolve([1, 2, 3, 4]),
map((a) => a + 10),
filter(a => a % 2 === 0),
reduce(sum),
); // 26

// if you want to use asynchronous callback
await pipe(
Promise.resolve([1, 2, 3, 4]),
toAsync,
map(async (a) => a + 10),
filter(a => a % 2 === 0),
reduce(sum),
); // 26

// with toAsync
await pipe(
[Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4)],
toAsync,
map(a => a + 10),
filter(a => a % 2 === 0),
reduce(sum),
); // 26

Try It

see pipe, toAsync, map, filter