DataWeave Interview Question: Concatenate Elements of an Array
This article will help you practice your DataWeave skills in MuleSoft. We're going to use two different approaches to concatenate an array of letters.
Join the DZone community and get the full member experience.
Join For FreeThis article will help you practice your DataWeave skills in MuleSoft. Let's get started.
Input:
JSON
x
1
["m","u","l","e","s","o","f","t"]
Output:
JSON
xxxxxxxxxx
1
1
"mulesoft"
Let's talk about the solution now.
We will apply a reduce function to our input and add the value of the item with the value of the accumulator.
Approach 1 Code:
Java
xxxxxxxxxx
1
1
%dw 2.0
2
output application/json
3
---
4
payload reduce ((item, accumulator) -> accumulator ++ item)
Approach 2 Code:
Java
xxxxxxxxxx
1
1
%dw 2.0
2
output application/json
3
---
4
payload reduce ($$ ++ $)
Here, $$ stands for accumulator and $ stands for an item.
Output:
JSON
x
1
"mulesoft"
If you want reverse output then you can use any of the above approaches with a little modification.
Approach 1 Code:
Java
xxxxxxxxxx
1
1
%dw 2.0
2
output application/json
3
---
4
payload reduce ((item, accumulator) -> item ++ accumulator)
Approach 2 Code:
Java
xxxxxxxxxx
1
1
%dw 2.0
2
output application/json
3
---
4
payload reduce ($ ++ $$)
Output:
JSON
xxxxxxxxxx
1
1
"tfoselum"
Happy Learning!
Data structure
Interview (journalism)
Element
Java (programming language)
JSON
MuleSoft
Opinions expressed by DZone contributors are their own.
Comments