⚡ Asynchronous version of `Array.prototype.reduce`.

Warning

Unlike other async array methods, this runs sequentially because each step depends on the previous result.

Syntax

TypeScript
import { reduceAsync } from '@opentf/std';

reduceAsync<T, R>(
  arr: T[],
  cb: (acc: R, value: T, index: number) => Promise<R>,
  initialValue: R
): Promise<R>;

Parameters

  • arr: The array to iterate over.

  • cb: An async callback function (accumulator, value, index).

  • initialValue: The initial value of the accumulator.

Returns

A Promise that resolves to the final accumulated value.

Sparse array holes are skipped, and when no initial value is provided the first present element becomes the accumulator, matching native Array.prototype.reduce() behavior.

Examples

TypeScript
const items = [1, 2, 3];
const sum = await reduceAsync(items, async (acc, n) => {
  return acc + n;
}, 0); //=> 6
Last updated on
Edit this page