Skip to content

reduce()

Info

New in Atfinity 17.

Description

reduce() folds a list into a single value by threading an accumulator through the list, left to right. Unlike map(), which processes each element independently, reduce() lets each step build on the result of the previous one, so it can express running totals, products, and stateful checksums.

The arrow function takes two arguments: the accumulator and the current element. reduce() also takes an initial accumulator value, which is returned unchanged for an empty list.

Syntax

list.reduce(initial, (accumulator, current) => expression)

Returns: the final accumulator value.

Example

(1, 2, 3, 4, 5).reduce(0, (acc, x) => acc + x)

Returns 15, the sum.

(1, 2, 3, 4, 5).reduce(1, (acc, x) => acc * x)

Returns 120, the product.

('a', 'b', 'c').reduce('', (acc, x) => concat(acc, x))

Returns 'abc'.

Stateful checksums

reduce() can express checksums whose steps depend on the previous result, which map() cannot. For example, the ISO 7064 MOD 11,10 scheme (used by some national tax numbers) carries a running product across the digits:

digits.reduce(10, (product, digit) => (((digit + product - 1) % 10 + 1) * 2) % 11)