The basics of Reduce, a MuleSoft DataWeave Operator

Share on facebook
Share on google
Share on twitter
Share on linkedin

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.

About us

Bits In Glass is an award-winning software consulting firm. We combine our deep industry expertise and experience with the best names in technology to provide innovative solutions to your unique business challenges. Our expert consultants excel at solving complex technical problems across industries and verticals, specializing in healthcare, financial services, insurance, and the public sector. Let us help you improve operations, drive better customer experiences, and return more to your bottom line.

Subscribe to Bits In Glass

Get the latest news and updates directly in your inbox.

Check out our video library!

Learn how Appian helped top brands gain success.