October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk14 min

Comparing Two Arrays Using Dataweave

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Comparing two arrays in DataWeave is a common requirement in MuleSoft transformations, especially when validating payloads, reconciling records, detecting changes, or preparing data for downstream systems. The right approach depends on whether you care about exact equality, missing values, object keys, duplicate entries, or the order of items.

DataWeave provides several practical tools for these scenarios, from simple equality checks to functions like filter, contains, map, and set-style operations. With a clear comparison strategy, you can handle both simple arrays and arrays of objects in a predictable, readable way.

As an Amazon Associate I earn from qualifying purchases.

Understanding Array Comparison in DataWeave

Array comparison in DataWeave depends on what you mean by “the same.” Two arrays can be identical element by element, contain the same values in a different order, share only some values, or contain objects that should be matched by a field such as id, sku, or email. In MuleSoft transformations, being clear about the comparison goal helps you choose between operators such as ==, functions such as filter, contains, map, and set-like operations built from these functions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The strictest comparison is direct equality. DataWeave’s == operator compares arrays by value and by position. This means [1, 2, 3] == [1, 2, 3] returns true, while [1, 2, 3] == [3, 2, 1] returns false. This behavior is useful when the order itself has meaning, such as validating a generated sequence, comparing ordered line items, or checking whether a payload matches an expected test fixture exactly.

Many integration scenarios need a looser comparison. For example, a product feed from one system may return item IDs in a different order than another system, while still representing the same set of products. In that case, sorting both arrays before comparing can be enough for simple scalar values: [3, 1, 2] orderBy $ == [1, 2, 3] orderBy $. For arrays of objects, sorting usually requires a specific field, such as items orderBy $.id, so that the comparison is deterministic.

Another common task is checking membership rather than full equality. If you want to know which values from one array do not exist in another, you can combine filter and contains. For example, left filter !(right contains $) returns items in left that are missing from right. This pattern is useful for finding missing IDs, removed permissions, new records, or records that failed to synchronize between systems.

Common comparison goals

  • Exact match: Use == when both values and order must match.
  • Same values, any order: Sort both arrays first, then compare.
  • Missing items: Use filter with contains to calculate differences.
  • Object matching: Compare selected fields, such as IDs, instead of entire objects.
  • Duplicate-aware comparison: Count occurrences when repeated values matter.

Arrays of objects require extra care because two objects are equal only when their compared structure and values align. If one system sends { id: 1, name: "A" } and another sends { id: 1, name: "A", status: "active" }, direct object comparison will not treat them as the same object. In those cases, extract the key fields first, such as orders map $.id, or compare objects by a composite key like customerId ++ "-" ++ orderId.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Null values and empty arrays also affect comparison results. An empty array [] is not the same as null, and calling array functions on null can produce errors unless you provide a default. In practical transformations, it is common to normalize inputs with payload.items default [] before comparing. This keeps the comparison predictable when optional fields are missing from a request, response, or database result.

Checking Whether Two Arrays Are Equal

The simplest way to compare two arrays in DataWeave is to use the equality operator, ==. This checks whether both arrays contain the same values in the same order. For arrays of simple values, such as strings, numbers, or booleans, this is usually enough when the sequence matters.

For example, the following expression returns true because both arrays have the same values at the same positions:

%dw 2.0
output application/json
---
[1, 2, 3] == [1, 2, 3]

The next comparison returns false, even though both arrays contain the same numbers, because the order is different:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

%dw 2.0
output application/json
---
[1, 2, 3] == [3, 2, 1]

This behavior is useful when comparing ordered data, such as line items in a submitted order, workflow steps, ranked results, or values exported from a system where position has meaning. If position does not matter, direct equality is often too strict and should be replaced with a sorting or set-style comparison.

Comparing Arrays After Sorting

When two arrays should be considered equal regardless of order, sort them before comparing. This works well for arrays of scalar values where duplicates still matter.

%dw 2.0
output application/json
var first = ["blue", "red", "green"]
var second = ["green", "blue", "red"]
---
(first orderBy $) == (second orderBy $)

This returns true because both arrays contain the same strings after sorting. If one array has an extra duplicate value, the result remains false:

%dw 2.0
output application/json
var first = ["red", "blue", "blue"]
var second = ["blue", "red"]
---
(first orderBy $) == (second orderBy $)

Comparing Arrays of Objects Exactly

For arrays of objects, == compares each object as part of the array structure. The field values must match, and the objects must appear in the same array position. In many MuleSoft transformations, this is useful for validating whether an incoming payload matches an expected structure exactly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

%dw 2.0
output application/json
var expected = [
{ id: 1, status: "ACTIVE" },
{ id: 2, status: "PENDING" }
]
var actual = [
{ id: 1, status: "ACTIVE" },
{ id: 2, status: "PENDING" }
]
---
expected == actual

If object order can vary, sort both arrays by a stable field before comparing:

%dw 2.0
output application/json
var expected = [
{ id: 1, status: "ACTIVE" },
{ id: 2, status: "PENDING" }
]
var actual = [
{ id: 2, status: "PENDING" },
{ id: 1, status: "ACTIVE" }
]
---
(expected orderBy $.id) == (actual orderBy $.id)

Normalizing Values Before Equality Checks

In real integrations, values may differ only by case, surrounding spaces, or formatting. Normalize the arrays before comparing so that the equality check reflects the business rule instead of the raw input format.

%dw 2.0
output application/json
var first = [" SKU-1 ", "sku-2"]
var second = ["sku-1", "SKU-2"]
---
(first map lower(trim($)) orderBy $) ==
(second map lower(trim($)) orderBy $)

Use direct equality when both order and duplicates are meaningful. Use sorting before equality when the same items can arrive in different positions. Use normalization when the source systems represent equivalent values with different casing, spacing, or formatting.

Finding Items Present in One Array but Not the Other

After checking equality, the next common task is identifying what exists in one array but not in another. In MuleSoft transformations, this is useful for detecting new records, removed values, missing identifiers, or payload changes between a source system and a target system. For simple arrays, DataWeave makes this straightforward with the subtraction operator, which returns values from the left array that are not present in the right array.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, if one payload contains incoming product IDs and another contains IDs already stored in a system, you can find the new IDs like this:

%dw 2.0
output application/json
var incomingIds = [101, 102, 103, 104]
var existingIds = [102, 104]
---
incomingIds -- existingIds

The result is:

[101, 103]

The same approach can be reversed to find values that exist in the second array but not in the first:

%dw 2.0
output application/json
var incomingIds = [101, 102, 103, 104]
var existingIds = [102, 104, 105]
---
{
newIds: incomingIds -- existingIds,
removedIds: existingIds -- incomingIds
}

This produces:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

{
"newIds": [101, 103],
"removedIds": [105]
}

For arrays of strings, the same pattern applies. DataWeave compares the actual values, so case and whitespace matter. For instance, "ABC" and "abc" are different values, and "A123" is not the same as "A123 ". When values may arrive with inconsistent formatting, normalize them before comparison.

%dw 2.0
output application/json
var sourceCodes = ["A123", "B456", "C789"]
var targetCodes = ["a123", "B456 "]
---
(sourceCodes map upper($)) -- (targetCodes map upper(trim($)))

In this example, the output is ["C789"] because both arrays are converted to uppercase and the target values are trimmed before the comparison. This kind of normalization is common when comparing data from external APIs, CSV files, or legacy systems.

When you need both sides of the difference in one result, structure the output clearly so downstream flows can act on it:

%dw 2.0
output application/json
var left = ["red", "blue", "green"]
var right = ["blue", "yellow"]
---
{
onlyInLeft: left -- right,
onlyInRight: right -- left,
inBoth: left filter (item) -> right contains item
}

This returns the values unique to each array and the values shared by both. The contains approach is especially readable when you want to build custom comparison rules later, such as comparing transformed values or checking part of an object.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For object arrays, the subtraction operator compares entire objects, not just one field. Two objects are considered different if any field value differs or if the structures are not the same. If you only want to compare by an identifier, such as id, sku, or email, first extract the keys or use filter with contains. This avoids accidentally treating the same business record as different just because a name, timestamp, or status field changed.

Comparing Arrays of Objects by a Specific Key

In MuleSoft integrations, arrays often contain objects rather than simple values. For example, one array may come from a CRM system and another from an ERP system, with each customer, product, or order represented as an object. In these cases, comparing the whole object is usually too strict because one system may include extra fields, different field names, or updated metadata. A more practical approach is to compare objects by a stable key such as id, sku, email, or orderNumber.

Suppose you have two arrays of customer objects and want to find which customers from the first array are missing in the second array based on id:

%dw 2.0
output application/json

var crmCustomers = [
{ id: "C001", name: "Ava", status: "active" },
{ id: "C002", name: "Ben", status: "inactive" },
{ id: "C003", name: "Mia", status: "active" }
]

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

var erpCustomers = [
{ id: "C001", name: "Ava Smith" },
{ id: "C003", name: "Mia Chen" }
]

---
crmCustomers filter (crmCustomer) ->
not ((erpCustomers map $.id) contains crmCustomer.id)

The result contains only the object with id C002. This pattern is common when identifying records that need to be created in a target system. The expression erpCustomers map $.id extracts the comparison keys from the second array, and contains checks whether each source object has a matching key.

For larger arrays or repeated lookups, it is often cleaner and more efficient to create a lookup object using groupBy. This avoids repeatedly mapping the target array inside the filter:

%dw 2.0
output application/json

var sourceProducts = [
{ sku: "P100", name: "Keyboard", price: 45 },
{ sku: "P200", name: "Mouse", price: 25 },
{ sku: "P300", name: "Monitor", price: 210 }
]

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

var targetProducts = [
{ sku: "P100", name: "Keyboard" },
{ sku: "P300", name: "Monitor" }
]

var targetBySku = targetProducts groupBy $.sku

---
sourceProducts filter (product) ->
isEmpty(targetBySku[product.sku] default [])

This returns the product with sku P200. Since groupBy creates an object where each s to an array of matching records, the lookup handles duplicate keys as well. Using default [] prevents null-related errors when the key is not present.

Finding Matching Objects by Key

You can also return records that exist in both arrays by reversing the condition. This is useful when you want to update records that already exist in the target system:

%dw 2.0
output application/json

var targetById = vars.targetCustomers groupBy $.id

---
vars.sourceCustomers filter (customer) ->
not isEmpty(targetById[customer.id] default [])

If you need to combine data from both matching objects, use map after filtering, or directly look up the matching target record:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

%dw 2.0
output application/json

var targetById = vars.targetCustomers groupBy $.id

---
vars.sourceCustomers map (customer) -> do {
var match = (targetById[customer.id] default [])[0] default {}
---
customer ++ {
targetStatus: match.status default null,
existsInTarget: not isEmpty(match)
}
}

  • Use map $.key with contains for small, simple comparisons.
  • Use groupBy when comparing larger arrays or when the lookup is reused.
  • Use default [] when a key may not exist in the lookup object.
  • Compare by stable business identifiers rather than fields that may change, such as display names or descriptions.

Handling Order, Duplicates, and Null Values

Array comparisons in DataWeave can produce different results depending on whether order, repeated values, and null entries should be treated as meaningful. Before choosing an operator or function, decide whether the array represents an ordered sequence, such as workflow steps, or an unordered collection, such as a list of product IDs. This decision changes how you normalize the data before comparing it.

Ignoring Order When Comparing Arrays

If two arrays contain the same values but in different positions, the equality operator returns false. For example, [1, 2, 3] == [3, 2, 1] is false because DataWeave compares arrays position by position. When order should not matter, sort both arrays first:

%dw 2.0
output application/json
var a = [3, 1, 2]
var b = [1, 2, 3]
---
(a orderBy $) == (b orderBy $)

For arrays of objects, sort by a stable field before comparing. This is useful when records arrive from different systems in different order but represent the same entities:

%dw 2.0
output application/json
var source = [
{ id: "B2", name: "Mouse" },
{ id: "A1", name: "Keyboard" }
]
var target = [
{ id: "A1", name: "Keyboard" },
{ id: "B2", name: "Mouse" }
]
---
(source orderBy $.id) == (target orderBy $.id)

Handling Duplicate Values

Duplicates require extra care because set-style checks can hide differences. For instance, [1, 1, 2] and [1, 2] contain the same distinct values, but they are not equivalent if quantity matters. Using distinctBy is appropriate only when duplicates should be ignored:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

%dw 2.0
output application/json
var a = [1, 1, 2]
var b = [2, 1]
---
(a distinctBy $ orderBy $) == (b distinctBy $ orderBy $)

When duplicates matter, compare grouped counts instead. This pattern works well for validating item quantities, repeated codes, or duplicate identifiers:

%dw 2.0
output application/json
var a = ["A", "A", "B"]
var b = ["B", "A", "A"]
fun counts(items) =
items groupBy $ mapObject ((value, key) -> sizeOf(value))
---
counts(a) == counts(b)

Handling Null and Missing Values

null is a real value in DataWeave, so [null] is not the same as []. If null entries should be ignored, filter them out before comparing. This is common when comparing payloads from APIs that include optional fields or placeholder values:

%dw 2.0
output application/json
var a = [1, null, 2]
var b = [2, 1]
---
((a filter $ != null) orderBy $) == ((b filter $ != null) orderBy $)

For arrays of objects, normalize fields that may be missing or null. The default operator can make comparisons predictable by replacing absent values with a consistent fallback:

%dw 2.0
output application/json
var a = [{ id: 1, status: null }]
var b = [{ id: 1 }]
fun normalize(items) =
items map {
id: $.id,
status: $.status default "UNKNOWN"
}
---
normalize(a) == normalize(b)

In MuleSoft transformations, the safest approach is to normalize first, then compare. Sort arrays when order should be ignored, preserve duplicates when counts matter, use distinctBy only when repeated values are irrelevant, and explicitly decide how null or missing fields should behave.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choosing the Right Comparison Approach

The best way to compare two arrays in DataWeave depends on what the transformation needs to prove. A strict equality check is useful when both arrays must contain the same values in the same sequence. A difference check is better when the goal is to identify missing or extra records. For arrays of objects, comparisons usually need to focus on stable fields such as id, sku, email, or another business key instead of comparing the whole object.

Match the method to the business requirement

Requirement Recommended approach Typical DataWeave pattern
Arrays must be identical, including order Use direct equality payload.a == payload.b
Arrays contain the same scalar values, order does not matter Sort both arrays before comparing payload.a orderBy $ == payload.b orderBy $
Find values in one array but not another Use filtering with contains payload.a filter !(payload.b contains $)
Compare object arrays by identifier Extract keys or filter by key match orders filter !(customers.id contains $.customerId)
Respect duplicate counts Group and compare occurrence totals groupBy followed by count comparison

For simple arrays such as strings, numbers, or codes, keep the expression compact. For example, if an API sends selected product codes and the system needs to detect unsupported codes, a filter is usually enough: vars.incomingCodes filter !(vars.allowedCodes contains $). This returns only the values that need attention and avoids unnecessary object-level comparison.

For arrays of objects, avoid comparing entire records unless every field is expected to match exactly. In integration flows, records often contain fields that change between systems, such as timestamps, status labels, audit fields, or formatting differences. Comparing by a stable key is usually safer: payload.sourceOrders filter !(payload.targetOrders.orderId contains $.orderId). When field-level validation is required, first match by key, then compare selected attributes such as amount, currency, or status.

Ordering and duplicates should be handled deliberately. If order has no business meaning, normalize the arrays before comparison by sorting scalar values or sorting objects by a key. If duplicates matter, sorting alone may not be enough unless the duplicate values remain visible in the final comparison. For object duplicates, group records by the selected key and compare counts, for example when checking whether shipment lines, invoice lines, or entitlement records were replicated correctly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Use == when exact structure, values, and order must match.
  • Use filter and contains when finding missing or unexpected scalar values.
  • Use key-based matching when comparing arrays of objects from different systems.
  • Use sorting when order should be ignored.
  • Use grouping when duplicate counts are part of the validation.

In MuleSoft transformations, clear array comparison makes payload validation easier to maintain. Choose the smallest expression that matches the requirement, normalize the data only when needed, and compare stable fields instead of full records when systems represent the same entity differently.

Frequently Asked Questions

How do I check if two arrays contain the same values in DataWeave?

If order matters, you can compare them directly with array1 == array2. If order should be ignored, sort both arrays first, such as array1 orderBy $ == array2 orderBy $. This works well for simple arrays like strings, numbers, or booleans.

How can I find values that exist in one array but not the other?

Use the subtraction operator for simple arrays, for example array1 -- array2 to return items from the first array that are not in the second. To get differences from both sides, run it both ways: array1 -- array2 and array2 -- array1. This is useful when comparing lists of IDs, codes, or names.

How do I compare two arrays of objects by an ID field?

Map each object array to the key you want to compare, such as payload.a.id or payload.a map $.id, then compare those key arrays. For example, use (array1 map $.id) -- (array2 map $.id) to find IDs missing from the second array. If you need the full objects back, filter the original array using those missing IDs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does DataWeave array comparison care about order and duplicates?

Direct equality checks care about both order and duplicate occurrences. For example, [1, 2, 2] == [2, 1, 2] returns false because the order is different. If order does not matter but duplicates do, sort both arrays before comparing; if duplicates should be ignored, apply distinctBy $ before comparison.

What is the safest way to compare arrays that might be null?

Default null values to empty arrays before comparing, such as (vars.firstArray default []) and (vars.secondArray default []). This avoids runtime errors when using operators like --, map, or filter. It also makes the transformation behavior clearer when a source field is missing.

Bottom Line

Comparing arrays in DataWeave comes down to choosing the right approach for the question you need to answer: use equality for exact matches, set-style operations for simple differences, and key-based filtering or grouping when working with arrays of objects. Always decide whether order, duplicates, and null values should matter before writing the transformation.

For MuleSoft projects, keep comparisons explicit and easy to read so future changes are safer to make. Start with the simplest operator or function that fits your data, then move to key-based matching or duplicate-aware when the payload requires it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.