The basics of Reduce, a MuleSoft DataWeave Operator
By Brian Labelle
Reduce allows us to iterate an array to accumulate a result. There are a few array operators like filter and map that do similar functions. You can use reduce to filter an array or map an array because you can reduce an array into another array but that wouldn’t be best practice. Ideally, you want to use reduce to produce a single result.
Here are some examples of using reduce with an array of numbers.
Which will produce these results:
If you have a shop with many DataWeave developers (more than three) I’d go with the short form of reduce otherwise the long form is more intuitive to a non-DataWeave developer trying to maintain the code.
Using the long form, “acc” is the accumulator and “val” is the value of each item in the array. When the values in your array are numbers, the first value will be zero. If your values are strings then the first value will be “”. You can start with a value other than 0 by setting acc=2.
From the examples above, I would recommend using the sum operator instead of reduce because it is clearer what you are trying to do in the code.
Reduce can also be used to process strings, by using the ++ operator. Below are some interesting examples that show how this can be done. Once again it is better practice to use the string operator joinBy which makes the intention of your code clearer.
which produces the following results:
Reduce can be useful when you need to apply a function to every item in the array, for example, applying a tax rate with rounding to each value, to ensure you get the correct rounding for your total result. Next up I’ll be writing an article about the more advanced uses of reduce.
About the author
Brian is a MuleSoft Practice Lead at Bits In Glass. He’s as excited about toying around with DataWeave as he was pushing and popping stacks of bits into registers in the early days of coding. He has seven siblings and four children so working as a team is second nature to him.