Skip to main content

$$reduce

Reduce an array with an initial value (identity) and a context transformer to a single value

Usage​

{ 
"$$reduce": /* Array of elements */,
"to": /* Transformer(##accumulator,##current,##index) */,
"identity": /* any */
}
"$$reduce(<to>,<identity>):{input}"

Returns​

The reduced value (type of to or identity)

Arguments​

ArgumentTypeValuesRequired / Default ValueDescription
PrimaryarrayYesArray of elements
toTransformer(##accumulator,##current,##index)YesTransformer to apply on each element (with last accumulation) to get the next accumulation
  • ##accumulator - Previously accumulated value
  • ##current - Current element
  • ##index - Current index
identityanyYesInitial value to start the accumulation with

Examples​

Input

Definition

Output

{
"items": [
{
"id": "aaa",
"amount": 10
},
{
"id": "bbb",
"amount": 20
}
]
}
{
"$$reduce": "$.items",
"identity": 0,
"to": {
"$$math": [
"##accumulator",
"+",
"##current.amount"
]
}
}
30
{
"items": [
{
"id": "aaa",
"amount": 10
},
{
"id": "bbb",
"amount": 20
}
]
}
{
"$$reduce": "aaa",
"identity": "bbb",
"to": "##current"
}
null
{
"items": [
{
"id": "aaa",
"amount": 10
},
{
"id": "bbb",
"amount": 20
}
]
}
"$$reduce('$$math(##accumulator,+,##current.amount)',0):$.items"
30