# `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.

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.

Because this method scans the full set, the query can time out for large sets.

## 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
}``````