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.
0 Comments