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
[1,2,3]
%dw 2.0
output json
---
payload reduce (n, total) -> total + n
6
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 reduce
.
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
or
Array<T> reduce( (item: T, accumulator: T) -> T): T | Null
Here
Lets see the use case where
acc value is not initialized
Dataweave:
%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
Dataweave:
%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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…