Nav

reduce

reduce(Array<T>, (item: T, acumulator: T) → T): T | Null

Apply a reduction to the array using just two parameters: the accumulator ($$), and the value ($). By default, the accumulator starts at the first value of the array. If the array is empty and no default value was set to the accumulator then null value is returned.

Transform

        
     
1
2
3
4
%dw 2.0
output application/json
---
sum: [0, 1, 2, 3, 4, 5] reduce ($$ + $)
Output

        
     
1
2
3
{
  "sum": 15
}
Transform

        
     
1
2
3
4
%dw 2.0
output application/json
---
concat: ["a", "b", "c", "d"] reduce ($$ ++ $)
Output

        
     
1
2
3
{
  "concat": "abcd"
}

In some cases, you may not want to use the first element of the array as an accumulator. To set the accumulator to something else, you must define this in a lambda.

Transform

        
     
1
2
3
4
%dw 2.0
output application/json
---
concat: ["a", "b", "c", "d"] reduce ((val, acc = "z") -> acc ++ val)
Output

        
     
1
2
3
{
  "concat": "zabcd"
}

In other cases, you may want to turn an array into a string keeping the commas in between. The example below defines a lambda that also adds commas when concatenating.

Transform

        
     
1
2
3
4
%dw 2.0
output application/json
---
concat: ["a", "b", "c", "d"] reduce ((val, acc) -> acc ++ "," ++ val)
Output

        
     
1
2
3
{
  "concat":  "a,b,c,d"
}
reduce(Array<T>, (item: T, acumulator: A) → A): A