🚀 DIGITAL TECH eBOOKS

Learn. Practice. Build.

Practical eBooks, interview questions, real-world projects and free learning resources for developers.

✓ Practical Content    ✓ Interview Focused    ✓ Real-World Examples

reduce() in DataWeave 2.0 — Calculate Totals from an Array

reduce() in DataWeave 2.0 — Calculate Totals from an Array




When building MuleSoft integrations, you often need to calculate a total, combine values, or accumulate information from an array. DataWeave provides the reduce() function for exactly these types of transformations.

In this practical example, we will calculate the total order amount from an array of orders.


🔹 What Is reduce()?

The reduce() function processes the elements of an array one by one and maintains an accumulated result.

A simple way to remember it is:

reduce() = Process multiple values → produce one accumulated result

It is particularly useful for totals, calculations, concatenation and other accumulator-based transformations.


📥 Input JSON

[
  {
    "orderId": "ORD001",
    "amount": 500
  },
  {
    "orderId": "ORD002",
    "amount": 750
  },
  {
    "orderId": "ORD003",
    "amount": 250
  }
]

Our requirement is to calculate the total amount of all orders.


💻 DataWeave 2.0 Solution

%dw 2.0
output application/json
---
payload reduce ((item, total = 0) -> total + item.amount)

📤 Output

1500

The function processes each order and keeps adding its amount to the accumulated total.


🔍 How Does It Work?

Step 1 — Initial Value

total = 0

The accumulator starts at zero.

Step 2 — Process the First Record

0 + 500 = 500

Step 3 — Process the Second Record

500 + 750 = 1250

Step 4 — Process the Third Record

1250 + 250 = 1500

Therefore, the final result is:

1500

🔹 Understanding the Parameters

Consider this expression:

payload reduce ((item, total = 0) -> total + item.amount)

Here:

  • item represents the current array element.
  • total represents the accumulated value.
  • total = 0 provides the initial accumulator value.
  • total + item.amount calculates the next accumulated value.

🏢 Real-World MuleSoft Example

Imagine an e-commerce Process API receives orders from Salesforce Commerce Cloud and needs to calculate the total order value before sending information to an ERP system.

The incoming payload could contain multiple order lines:

[
  {
    "product": "Laptop",
    "quantity": 2,
    "unitPrice": 800
  },
  {
    "product": "Mouse",
    "quantity": 3,
    "unitPrice": 25
  },
  {
    "product": "Keyboard",
    "quantity": 1,
    "unitPrice": 75
  }
]

We can calculate the total using:

%dw 2.0
output application/json
---
payload reduce (
  (item, total = 0) ->
    total + (item.quantity * item.unitPrice)
)

Output

1750

Calculation:

(2 × 800) + (3 × 25) + (1 × 75)
= 1600 + 75 + 75
= 1750

🔹 reduce() vs sum()

If your requirement is simply to add numeric values, DataWeave also provides sum().

For example:

%dw 2.0
output application/json
---
[100, 200, 300] sum

Output:

600

So when should you use reduce()?

  • Use sum() for straightforward numeric totals.
  • Use reduce() when you need custom accumulation logic.

🔹 reduce() Can Do More Than Addition

The accumulator does not have to be a number. You can use reduce() for custom transformations.

For example, concatenate values from an array:

%dw 2.0
output application/json
---
["MuleSoft", "DataWeave", "API"]
  reduce ((item, result = "") ->
    if (result == "")
      item
    else
      result ++ " | " ++ item
  )

Output

"MuleSoft | DataWeave | API"

🎯 MuleSoft Interview Question

What is the purpose of reduce() in DataWeave?

Answer: reduce() iterates through an array while maintaining an accumulator and returns the final accumulated result. It is useful when multiple input elements need to be combined into a single result using custom logic.


⚠️ Common Mistake

A common mistake is choosing reduce() when a simpler DataWeave function already solves the problem.

For example, if you only need the sum of numeric values, sum() is usually clearer:

[10, 20, 30] sum

Use reduce() when you actually need custom accumulator logic.


💡 Production Tip

For large enterprise payloads, always consider the memory and processing characteristics of the transformation. If a simpler DataWeave function can express the requirement clearly, prefer the simpler solution.


🚀 Final Takeaway

reduce() = Iterate + Accumulate + Return One Result

The most important pattern to remember is:

payload reduce ((item, accumulator = initialValue) ->
  updatedAccumulator
)

Once you understand the accumulator concept, reduce() becomes a powerful tool for advanced DataWeave transformations.


📚 Want to Practice More DataWeave?

Practice DataWeave with 1000 real-world problems with complete solutions, from beginner concepts to advanced enterprise transformations.

👉 Get 1000 Problems to DataWeave Mastery →


Follow Digital Tech eBooks for more MuleSoft, DataWeave, API-led connectivity, connectors, deployment and real-world integration tutorials.

Post a Comment

0 Comments