reduce()
Reduce a set to a single, accumulated value by applying a function to each element. Iterates through elements from left to right. Uses the first element as the initial value.
Description
The reduce()
method iterates through each element in a set 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 set
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 set serves as the initial accumulator.
-
The current element’s value.
The method returns the result of the last iteration. The calling set isn’t changed.
Because this method scans the full set, it returns an error if there are more than 16,000 documents in the set. This method can timeout for large sets under that limit.
Fold family methods
FQL supports several methods for folds, which iteratively reduce a set to a single value. These methods include:
The methods are similar but have the following differences:
-
fold()
andfoldRight()
accept an initial seed value and use it as the initial accumulator.reduce()
andreduceRight()
use the set’s first element as the initial accumulator. -
fold()
andreduce()
iterate through the set’s elements from left to right.foldRight()
andreduceRight()
iterate through the set’s elements from right to left.
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
reducer |
Yes |
Anonymous FQL function to call on each element in the set. |
Examples
-
Starting with the following product prices:
// Gets a set of the first nine `Product` collection // documents and projects the `price` field. Product.all().take(9) { price }
{ data: [ { price: 6.98 }, { price: 24.99 }, { price: 4.99 }, { price: 3.99 }, { price: 0.35 }, { price: 3.49 }, { price: 2.99 }, { price: 1.49 }, { price: 23.99 } ] }
-
Use
reduce()
to find the maximum price in the set:Product.all().take(9).reduce((s, v) => { if (v.price > s.price) { v } else { s } }) {price}
{ price: 24.99 }
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!