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.

The calling Array isn’t changed.

Parameters

Parameter Type Required Description

reducer

Function

Yes

Function to invoke for each element in the calling 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"

This shows the steps of each iteration of the reducer Function:

Reducer call Accumulator value Current value Array index Result

First call

""

"A"

0

"A"

Second call

"A"

"B"

1

"AB"

Third call

"AB"

"C"

2

"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!