Skip to content

reduce() function

也称为 foldl,此方法将值列表归约为单个值。

Signature:

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

Example

You can reduce values into homogeneous type.

ts
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.

ts
// 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.

ts
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.

ts
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

Released under the Apache-2.0 License.