Skip to main content

$reduce

The $reduce operator applies a function to each element in an array to reduce it to a single value.

Input

  • An array containing an array to reduce, an initial value, and a reducer function

Output

  • A single value resulting from the reduction

Examples

Sum Array Values

{
  "$reduce": [
    [1, 2, 3, 4, 5],
    0,
    {
      "$add": [
        {
          "$var": ["accumulator"]
        },
        {
          "$var": ["currentValue"]
        }
      ]
    }
  ]
}
Result: 15

Concatenate Strings

{
  "$reduce": [
    ["a", "b", "c"],
    "",
    {
      "$concat": [
        {
          "$var": ["accumulator"]
        },
        {
          "$var": ["currentValue"]
        }
      ]
    }
  ]
}
Result: "abc"