reduce()

Apply a reducer Function to each Array element to get a single value.

Signature

reduce(reducer: (accum: Any, value: Any) => Any): Any

Description

The reduce() method applies a reducer Function to each Array element, from left to right, by passing the reducer value returned from the previous iteration and the next Array element as parameters. The result of the last calculation is the returned value. If the array has only one element the first element is returned. If the array has no elements an error is returned. A mental model for reduce() is that it is fold() where the first element is used as the seed.

The calling array isn’t changed.

Parameters

Parameter Type Required Description

reducer

Function

Yes

Function to invoke for each element in the calling array, starting with the first value in the array.

reducer parameters:

Parameter Type Required Description

accum

Any

Yes

Value returned by the previous invocation of reducer.

val

Any

Yes

Current Array element to be evaluated.

Return value

Type Description

Any

Result of the last reducer calculation.

Examples

Reduce the Array elements to a single value:

["A", "B", "C"].reduce((prev, cur) => prev + cur)
"ABC"

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!