Reduce Function

 

Reduce function is used to do any computation while iterating on an array, computation result is not lost while iteration. 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

  • Array – is the array on which we want to apply reduce function
  • Item
    • 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.
  • Iteration
    • 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

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

more details

  
Thank you for taking out time to read the above post. Hope you found it useful. In case of any questions, feel free to comment below. Also, if you are keen on knowing about a specific topic, happy to explore your recommendations as well.
 
For any latest updates or posts on our website, you can follow us on LinkedIn. Look forward to connecting with you there.


Share this:
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rizwan
Rizwan
7 months ago

Hello Admin,
while concatenating using reduce function getting the output as “54321”
—-
if acc value is not initialized
acc -> $$ will take the 1st item value 
$ will take the 2nd item value

[1,2,3,4,5] reduce ((item,acc) -> item ++ acc)