Check out v4 of the Fauna CLI

v4 of the Fauna CLI is now in beta.

The new version introduces enhancements to the developer experience, including an improved authentication workflow. To get started, check out the CLI v4 quick start.

array.reduce()

This method operates on an array. You typically fetch documents from a collection as a set, not an Array. For the equivalent Set method, see set instance methods.

For differences between Sets and Arrays, see Sets vs. Arrays.

Reduce an Array to a single, accumulated value by applying a provided function to each element. Iterates through elements from left to right. Uses the first element as the initial value.

Signature

reduce(reducer: ((A, A) => A)) => A | Null

Description

Iterates through each element in an Array to perform a rolling operation. For example, you can use reduce() to calculate a rolling sum, concatenate elements, or perform complex transformations.

reduce() calls a reducer callback function on every element of the Array from left to right. The reducer function takes two arguments:

  • The accumulator that holds the running result from previous iterations. The first element in the Array serves as the initial accumulator.

  • The current element’s value.

The method returns the result of the last iteration. The calling Array isn’t changed.

Fold family methods

FQL supports several methods for folds, which iteratively reduce an Array to a single value. These methods include:

The methods are similar but have the following differences:

Parameters

Parameter Type Required Description

reducer

Function

Yes

Anonymous FQL function to call on each element in the Array.

Reducer function parameters:

Parameter Type Required Description

accumulator

Any

Yes

Value returned by the previous reducer function call. On the first call, seed is passed as the accumulator.

current

Any

Yes

The current element’s value.

Return value

One of:

Type Description

Generic

Result of the last reducer function call.

Null

Returns Null if the calling Array is empty.

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!