Skip to main content

Function: reduce()

reduce<ElementType, MappedType>(iterable: IterableResolvable<ElementType>, callbackFn: (accumulator: MappedType, currentValue: ElementType, currentIndex: number) => MappedType, initialValue?: MappedType): MappedType

Consumes the iterable and reduces it to the reducer function's result.

Type parameters

Type parameter


iterableIterableResolvable<ElementType>An iterator to reduce.
callbackFn(accumulator: MappedType, currentValue: ElementType, currentIndex: number) => MappedTypeA function to execute for each element produced by the iterator. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce().
initialValue?MappedTypeA value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first element as currentValue. If initialValue is not specified, accumulator is initialized to the first element, and callbackFn starts executing with the second element as currentValue. In this case, if the iterator is empty (so that there's no first value to return as accumulator), an error is thrown.




import { reduce } from '@sapphire/iterator-utilities';

const iterable = [1, 2, 3, 4, 5];
console.log(reduce(iterable, (accumulator, currentValue) => accumulator + currentValue));
// Output: 15


If initialValue is not provided, the first element of the iterator is used as the initial value of accumulator, consuming the first element.