DataWeave Interview Question: Reverse an Array After Combining Its Elements
This article will help you practice your DataWeave skills in MuleSoft. Use the article as a tutorial for learning more about DataWeave.
Join the DZone community and get the full member experience.
Join For FreeThis article will help you practice your DataWeave skills in MuleSoft. Use the article as a tutorial for learning more about DataWeave.
Let's get started.
Input:
[
"uat", ["sit", "qa", "prod"]
]
Output:
[
"prod",
"qa",
"sit",
"uat"
]
Let's talk about the solution now.
In the first step, we will combine all the elements of an array into a single array using flatten function.
Step 1 Code:
DataWeave Script
%dw 2.0
output application/json
var combinedPayload = (flatten(payload))
---
combinedPayload
Step 1 Output:
[
"uat",
"sit",
"qa",
"prod"
]
In the second step, we will reverse the contents of an array using the range selector.
Step 2 Code:
DataWeave Script
%dw 2.0
output application/json
var combinedPayload = (flatten(payload))
---
combinedPayload[(sizeOf(combinedPayload)) -1 to 0]
Step 2 Output:
[
"prod",
"qa",
"sit",
"uat"
]
We have used sizeOf function to get the size of our combinedPayload along with the range selector to get the array in reverse format.
Happy Learning!
Opinions expressed by DZone contributors are their own.
Comments