MuleSoft Working with Arrays
Arrays appear everywhere in integration work. Database queries return arrays of rows. REST APIs return arrays of products or customers. Batch jobs process arrays of records. DataWeave gives you powerful tools to navigate, transform, slice, and combine arrays efficiently.
Array Basics in DataWeave
An array is an ordered list of items enclosed in square brackets. Items can be any type: strings, numbers, booleans, objects, or even other arrays.
Array Types
// Array of strings:
["Pen", "Book", "Bag"]
// Array of numbers:
[10, 25, 3.5, 100]
// Array of objects (most common in integration):
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" },
{ "id": 3, "name": "Carol" }
]
// Nested array:
[ [1,2,3], [4,5,6], [7,8,9] ]
Accessing Array Elements
Use square brackets with an index number to access a specific element. Indexes start at zero. Use negative indexes to count from the end.
payload = ["Apple", "Banana", "Cherry", "Date"] payload[0] // "Apple" (first element) payload[2] // "Cherry" (third element) payload[-1] // "Date" (last element) payload[-2] // "Cherry" (second from last)
Array Slicing
Use the slice range [start to end] to extract a portion of an array.
payload = [10, 20, 30, 40, 50, 60] payload[0 to 2] // [10, 20, 30] (indexes 0, 1, 2) payload[2 to -1] // [30, 40, 50, 60] (from index 2 to end) payload[0 to -2] // [10, 20, 30, 40, 50] (all except last)
Checking Array Size
payload = [{ "id": 1 }, { "id": 2 }, { "id": 3 }]
sizeOf(payload) // 3
// Use in a condition:
if (sizeOf(payload) == 0) "No records found" else "Records found"
Checking if an Array Contains a Value
payload = ["admin", "editor", "viewer"] payload contains "editor" // true payload contains "owner" // false // Practical use: check if a user has a required role if (vars.userRoles contains "admin") "Access granted" else "Access denied"
flatten Operator
The flatten operator converts a nested array (array of arrays) into a single flat array.
flatten Example
Input: [ [1, 2, 3], [4, 5], [6, 7, 8, 9] ] DataWeave: %dw 2.0 output application/json --- flatten(payload) Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Real-World flatten: Collect All Tags from Multiple Posts
Input:
[
{ "title": "Post A", "tags": ["news", "tech"] },
{ "title": "Post B", "tags": ["finance", "news"] },
{ "title": "Post C", "tags": ["tech", "science", "ai"]}
]
DataWeave:
%dw 2.0
output application/json
---
flatten(payload map (post) -> post.tags)
Output:
["news", "tech", "finance", "news", "tech", "science", "ai"]
Removing Duplicates with distinctBy
From the above output, to get unique tags only: DataWeave: %dw 2.0 output application/json --- (flatten(payload map (post) -> post.tags)) distinctBy $ Output: ["news", "tech", "finance", "science", "ai"]
zip Operator: Merging Two Arrays
The zip operator pairs elements from two arrays by position. The first element of array A pairs with the first element of array B, and so on.
zip Example
DataWeave:
%dw 2.0
output application/json
---
zip(["Alice", "Bob", "Carol"], [101, 102, 103])
map (pair) -> { "name": pair[0], "id": pair[1] }
Output:
[
{ "name": "Alice", "id": 101 },
{ "name": "Bob", "id": 102 },
{ "name": "Carol", "id": 103 }
]
partition Operator
The partition operator splits an array into two groups: elements that match a condition (success) and those that do not (failure).
partition Example: Separate Valid and Invalid Records
Input:
[
{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": -5 },
{ "name": "Carol", "age": 25 },
{ "name": "Dave", "age": -1 }
]
DataWeave:
%dw 2.0
output application/json
---
payload partition (record) -> record.age > 0
Output:
{
"success": [
{ "name": "Alice", "age": 30 },
{ "name": "Carol", "age": 25 }
],
"failure": [
{ "name": "Bob", "age": -5 },
{ "name": "Dave", "age": -1 }
]
}
sumBy and countBy Functions
Input:
[
{ "product": "Pen", "qty": 10, "price": 1.5 },
{ "product": "Book", "qty": 3, "price": 12.0 },
{ "product": "Bag", "qty": 2, "price": 25.0 }
]
DataWeave:
%dw 2.0
output application/json
---
{
"totalItems": payload sumBy (i) -> i.qty,
"totalRevenue": payload sumBy (i) -> (i.qty * i.price),
"productCount": sizeOf(payload)
}
Output:
{
"totalItems": 15,
"totalRevenue": 91.0,
"productCount": 3
}
Building Dynamic Arrays
Sometimes you need to build an array where the number of elements is not known in advance. Use an array literal with computed elements.
// Create an array of the next 5 weekday dates from today:
%dw 2.0
output application/json
---
[0,1,2,3,4] map (n) -> (now() + |P$(n)D|) as Date {format: "yyyy-MM-dd"}
Array to Object Conversion
Convert an array of key-value pairs into a single object using reduce.
Input:
[
{ "key": "color", "value": "blue" },
{ "key": "size", "value": "large" },
{ "key": "brand", "value": "Acme" }
]
DataWeave:
%dw 2.0
output application/json
---
payload reduce ((item, acc = {}) -> acc ++ { (item.key): item.value })
Output:
{ "color": "blue", "size": "large", "brand": "Acme" }
Tips for Array Processing
- Always check array size before accessing by index to avoid null pointer errors.
- Use
filterbeforemapwhen you need to exclude records. This avoids transforming data you will discard anyway. - For very large arrays in production, consider Batch Processing instead of DataWeave in-memory operations.
