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<T>(f: SyncReducer<T, T>, iterable: Iterable<T>): T;

declare function reduce<T, Acc>(f: SyncReducer<Acc, T>, iterable: Iterable<T>): Acc;

declare function reduce<T>(f: SyncReducer<T, T>, iterable: AsyncIterable<T>): Promise<T>;

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

declare function reduce<T, Acc>(f: SyncReducer<Acc, T>, seed: Acc, iterable: Iterable<T>): Acc;

declare function reduce<T, Acc>(f: AsyncReducer<Acc, T>, iterable: AsyncIterable<T>): Promise<Acc>;

declare function reduce<T, Acc>(f: AsyncReducer<Acc, T>, seed: Acc | Promise<Acc>, iterable: AsyncIterable<T>): Promise<Acc>;

declare function reduce<T extends Iterable<unknown> | AsyncIterable<unknown>, Acc>(f: AsyncReducer<Acc, IterableInfer<T>>): (iterable: T) => ReturnValueType<T, Acc>;

declare function reduce<T extends Iterable<unknown> | AsyncIterable<unknown>>(f: AsyncReducer<IterableInfer<T>, IterableInfer<T>>): (iterable: T) => ReturnValueType<T>;

Example

You can reduce values into homogeneous type.

const sum = (a:number, b:number) => a + b;

// with implicit seed with first element
reduce(sum, [1, 2, 3, 4]); // 10

// with explicit seed
reduce(sum, 0, [1, 2, 3, 4]); // 10

You can reduce values into heterogeneous type.

// reduce { id: number; score: number; } to number
reduce((acc, value) => acc + value.score, 0, [
{ id: 0, score: 1 },
{ id: 5, score: 2 },
{ id: 9, score: 3 },
{ id: 3, score: 4 }
])

Omitting iterable will returns function, useful when using with pipe.

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

For backward compatibility, reduce can support partial lazy form. You may want to use reduceLazy to use seed.

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

Open Source Code