Skip to main content

Data transformation is a fundamental aspect of integration and data processing. In the realm of MuleSoft’s Anypoint Platform, DataWeave 2.0 is a versatile and powerful tool for handling data transformation tasks. One common operation is summing the elements of an array. In this article, we’ll guide you through the process of summing an array in DataWeave 2.0 with clear examples.

Understanding the reduce Function

To sum the elements of an array in DataWeave 2.0, we’ll use the reduce function. This function allows us to aggregate values in an array by applying a specified operation iteratively. The basic syntax for using reduce is as follows:

array reduce ((accumulator, current) -> accumulator + current)
  • array: The array you want to sum.
  • reduce: The function used to iterate over the elements.
  • accumulator: A variable that stores the cumulative result.
  • current: The current element being processed in the array.

Example 1: Summing Numeric Values

Let’s start with a simple example. Suppose you have an array of numbers and you want to find their sum.

%dw 2.0
output application/json
var numbers = [1, 2, 3, 4, 5]
numbers reduce ((acc, item) -> acc + item)

In this example:

  • numbers is an array containing [1, 2, 3, 4, 5].
  • The reduce function iterates through each element of numbers.
  • (acc, item) represents the accumulator (acc) and the current item in the array (item).
  • acc + item adds the current item to the accumulator.
  • The result is 15 (1 + 2 + 3 + 4 + 5), which is the sum of all the elements in the array.

Example 2: Summing an Array of Objects

DataWeave 2.0 is not limited to simple arrays of numbers; it can also handle more complex data structures. Consider an array of objects where each object has a value property:

%dw 2.0
output application/json
var objects = [
  { "value": 10 },
  { "value": 20 },
  { "value": 30 }
objects reduce ((acc, item) -> acc + item.value)

In this example:

  • objects is an array of objects, each containing a value property.
  • We use reduce to iterate over the objects and sum their value properties.
  • The result is 60 (10 + 20 + 30), which is the sum of the value properties in the array.


Summing an array in DataWeave 2.0 is a straightforward process using the reduce function. Whether you’re working with simple numeric arrays or more complex data structures, DataWeave 2.0 provides a flexible and efficient way to perform aggregation operations. By understanding the fundamentals of reduce, you can unlock the full potential of DataWeave for your data transformation needs.

Close Menu

Welcome to Coded Brainy

Coded Brainy Provides you with technical blogs

Coded Brainy