# `reduce()`

Collapse a Set to a single value by applying a Function to each Set value.

## Signature

reduce(reducer: (acc: B, value: A) => B): B

## Description

This method applies the reducer Function to each Set value, starting with the first value in the set.

Each reducer invocation is passed the current accumulator acc and the first Set value, and returns a new accumulator. The new accumulator is passed to the next reducer invocation with the next Set value.

The accumulator returned by the final reducer invocation is the return value. If the set has only one item the reducer returns the first item. If the set is empty an error is returned. A mental model for `reduce()` is that it is `fold()` where the first item is used as the seed.

Because this method scans the full set, it returns an error if there are more than 16000 documents in the set. This method can timeout for large sets under that limit.

## Parameters

Parameter Type Required Description

reducer

Function

Yes

Anonymous Function to invoke for each Set value.

### reducer parameters:

Parameter Type Required Description

acc

Any

Yes

Value returned by the previous invocation of reducer.

value

Any

Yes

Current Set value.

## Return value

Type Description

Any

Result of the last reducer invocation.

## Examples

1. For these examples, the product prices are:

``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
}
]
}``````
2. Count the prices in the set:

``Product.all().take(9).reduce((s, v) => s + 1)``
``9``
3. Find the maximum price in the set:

``````Product.all().take(9).reduce((s, v) => {
if (v.price > s) { v.price } else { s }
})``````
``24.99``
4. Calculate the average price:

``````Product.all().take(9).reduce(
(s, v) => {
let count = s.count + 1
let total = s.total + v.price
{
count: count,
total: total,
average: total / count,
}
}
)``````
``````{
count: 9,
total: 73.26,
average: 8.14
}``````