How to separate an array based on the condition in Dataweave

In this article, let us see how can we separate a JSON array using the partition function in the Dataweave Arrays Module. The partition module separates an array into a success array (which satisfies the given condition) and a failure array (which does not satisfy the condition). It is a quick and easy way to differentiate arrays and use them for further transformations.

Also Read: How to format dates 📆 in Dataweave 2.0 Mule 4



Separate an array using a condition in Dataweave


Example 1:

In this example, we are separating an ArrayList on the criteria of odd numbers. The below code separates the list of numbers into odd numbers and even numbers.


Dataweave Code:
%dw 2.0
import * from dw::core::Arrays
output application/json
var arrayList = [12,34,45,67,2,0,1,43]
---
arrayList partition (n) -> isOdd(n)

Example 2:

In this example, we are separating the list of numbers using the integers criteria. All the integers from the ArrayList will be filtered out into the success array and remaining into the failure array. As the ArrayList contains only integers the failure array after applying partition function is empty.


Dataweave Code:
%dw 2.0
import * from dw::core::Arrays
output application/json
var arrayList = [12,34,45,67,2,0,1,43]
---
arrayList partition (n) -> isInteger(n)

Example 3:In this scenario, we are partitioning the ArrayList by the strings starting with "a" and the strings that do not start with "a".

Dataweave Code:
%dw 2.0
import * from dw::core::Arrays
output application/json
var arrayList = ["ab","ac","ad","bc","bd"]
---
arrayList partition (list) -> list startsWith("a")

Conclusion:

The above-given examples should help you in understanding the use of the partition function in Dataweave. To use the partition function we must import the arrays module by adding "import * from dw::core::Arrays" into the header of Dataweave code.



Post a Comment

0 Comments