Reduce function is used to do any computation while iterating on an array, so the computation result is not lost during iteration. For each element of the input array, in order, reduce applies the reduction lambda expression (function), then replaces the accumulator with the new result. The lambda expression can use both the current input array element and the current accumulator value.
Note that if the array is empty and no default value is set on the accumulator parameter, a null value is returned. Here’s its function signature:
reduce(Array<T>, ((T, R) -> R)): R
%dw 2.0 output json --- payload reduce (n, total) -> total + n
Let’s use this example to discuss how
reduce uses the lambda passed to it to generate the output. The lambda function is defined like this:
((T, R) -> R)
It takes in two parameters and returns one. The first parameter represents a particular item from the inbound Array. The second parameter, however, does not represent the current index. The second parameter represents the present value of the accumulator. What’s the accumulator? The accumulator is what stores what is potentially returned from
reduce. The job of the lambda is to return a new accumulator for each iteration. After the last iteration, the accumulator is what finally gets returned from
it’s a very helpful function where you have to do computation on some array element.
reduce(Array<T>, (item: T, accumulator: T) -> T): T | Null
Array<T> reduce( (item: T, accumulator: T) -> T): T | Null
- Array – is the array on which we want to apply reduce function
- item in the input array
- Refer as $
- Takes 1st array item value in case acc is defined
- Takes 2nd array item value in case acc is not defined
- Accumulator (acc)
- Store the results of lambda expression after each iteration in reduce function
- Refer as $$
- We can explicitly define the initial value like [2,3,3] reduce ((item, acc = “2”) → acc * item)
- If initial value is not defined then it will take the value of first item of array.
- no of item in array minus 1 in case acc is not initialized
- no of item in array in case acc is initialized
Lets see the use case where
acc value is not initialized
%dw 2.0 output application/json --- [2, 3] reduce ($ + $$) Here [2,3] – is the input array acc -> $$ will take the 1st item value = 2 (as acc is not initialized) $ will take the 2nd item value = 3 (as acc is not initialized) Loop count = no of item in array minus 1 (as acc is not initialized) = 2 – 1 = 1 Acc = ($=3 + $$=2) = 5 So result will be 5
acc value is initialized
%dw 2.0 output application/json --- [2,3] reduce ((item, acc = 4) -> acc + item) Here [2,3] – is the input array acc will take the initialized value = 4 item will take 1st item value = 2 (as acc is initialized) Loop count = no of item in array (as acc is initialized) = 2 Acc = acc + item -> 4 + 2 -> 6 Acc = acc + item -> 6 + 3 -> 9 So result will be 9
If you like my post please follow me to read my latest post on programming and technology.