fold()

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

Signature

fold(seed: B, reducer: (B, A) => B) => B

Description

The fold() method iterates through each element in an array to perform a rolling operation. For example, you can use fold() to calculate a rolling sum, concatenate elements, or perform complex transformations.

fold() calls a reducer callback function on each element of the array from left to right. The reducer function takes two arguments:

  • The accumulator that holds the running result from previous iterations. For the first iteration, a seed value serves as the initial accumulator.

  • The current element’s value from the array.

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

seed

Any

Yes

Initial accumulator value provided to the reducer function.

reducer

Function

Yes

Anonymous FQL function to call on each array element.

reducer 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

Type Description

Any

Result of the last reducer function call. For an empty array, the seed is returned.

Examples

let iter = [1, 2, 3]
iter.fold(100, (value, elem) => value + elem)
106

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!