Data Weave Solved Exercises in Mule 4 : Part-2

Rajeev Ranjan
7 min readJan 25, 2024

--

The power of Data Weave

There were few interesting challenge found over page: DataWeave — Practice Exercises (jerney.io) and Ace MuleSoft Interview: DataWeave Exercises in Mule 4 | MuleGuru here I tried to solved and capture the solutions below:

Exercise 1:

Add 1 to each value in the array [1,2,3,4,5]

Input

["1","2","3","4","5"]

Output

[
2,
3,
4,
5,
6
]

Solution

%dw 2.0
output application/json
---
payload map ((item, index) -> (item+1) as Number )
Data weave playground snapshot

Exercise 2:

Get a list of ids from

Input

[  { "id": 1, "name": "Archer" },  
{ "id": 2, "name": "Cyril" },
{ "id": 3, "name": "Pam" }
]

Output

[
{
"id": 1
},
{
"id": 2
},
{
"id": 3
}
]

Solution

%dw 2.0
output application/json
---
payload map ((item, index) ->
"id": item.id
)
Data weave playground snapshot

Exercise 3:

Input

[
{
"name": "Archer",
"jobs": [
{ "type": "developer" },
{ "type": "investor" },
{ "type": "educator" }
]
},
{
"name": "Cyril",
"jobs": [
{ "type": "developer" },
{ "type": "entrepreneur" },
{ "type": "lion tamer" }
]
}
]

Output

[
{
"num": 1
"name": "Archer",
"jobs": [
{ "num": 1, "type": "developer" },
{ "num": 2, "type": "investor" },
{ "num": 3, "type": "educator" }
]
},
{
"num": 2
"name": "Cyril",
"jobs": [
{ "num": 1, "type": "developer" },
{ "num": 2, "type": "entrepreneur" },
{ "num": 3, "type": "lion tamer" }
]
}
]

Solution

%dw 2.0
output application/json
---
payload map ((itemOuter, indexOuter) -> {
"num": indexOuter+1,
"name": itemOuter.name,
"jobs": itemOuter.jobs map ((itemInner, indexInner) ->{
"num": indexInner+1,
"type": itemInner."type"
} )
} )
Data weave playground snapshot

Exercise 4:

Remove Odd Values [101,204,305,4008,5009, 6004,70045,801,9034,1004]

Input

[101,204,305,4008,5009, 6004,70045,801,9034,1004]

Output

{
"even-1": [
[
204,
4008,
6004,
9034,
1004
]
],
"even-2": [
[
204,
4008,
6004,
9034,
1004
]
]
}

Solution

%dw 2.0
output application/json

fun removeOdd1(payload: Array): Array = payload filter ((item, index) -> isEven(item) )
fun removeOdd2(payload: Array): Array = payload filter ((item, index) -> !(isOdd(item)) )

---
{
"even-1":[removeOdd1(payload)],
"even-2":[removeOdd2(payload)],
}
Data weave playground snapshot

Exercise 5:

Remove Even Values [101,204,305,4008,5009, 6004,70045,801,9034,1004]

Input

[101,204,305,4008,5009, 6004,70045,801,9034,1004]

Output

{
"odd-1": [
[
101,
305,
5009,
70045,
801
]
],
"odd-2": [
[
101,
305,
5009,
70045,
801
]
]
}

Solution

%dw 2.0
output application/json

fun removeEven1(payload: Array): Array = payload filter ((item, index) -> isOdd(item) )
fun removeEven2(payload: Array): Array = payload filter ((item, index) -> !(isEven(item)) )

---
{
"odd-1":[removeEven1(payload)],
"odd-2":[removeEven2(payload)],
}
Data weave playground snapshot

Exercise 6:

Masked sensitive data in payload like email, phone and credit card. Along with format the phone and currency

Input

{
"employees": [
{
"id": "101",
"contact": {
"firstName": "John",
"lastName": "Grisham",
"email": "Grisham@gmail.com",
"phone": "1234567890"
},
"designation": "Engineer",
"salary": 20000,
"gender": "M",
"creditCard": "123456789012"
},
{
"id": "102",
"contact": {
"firstName": "Katherine",
"lastName": "Salvatore",
"email": "Katherine@gmail.com",
"phone": "8793214560"
},
"designation": "Manager",
"salary": 50000,
"gender": "F",
"creditCard": "123456789012"
}
]
}

Output

{
"employees": [
{
"id": "101",
"contact": {
"firstName": "JOHN",
"lastName": "G****",
"email": "****@gmail.com",
"phone": "(***)-(***)-7890"
},
"designation": "Engineer",
"salary": "₹ 20,000.00",
"gender": "M",
"creditCard": "(****)-(****)-9012"
},
{
"id": "102",
"contact": {
"firstName": "KATHERINE",
"lastName": "S****",
"email": "****@gmail.com",
"phone": "(***)-(***)-4560"
},
"designation": "Manager",
"salary": "₹ 50,000.00",
"gender": "F",
"creditCard": "(****)-(****)-9012"
}
]
}

Solution

%dw 2.0
output application/json

import * from dw::core::Strings
import * from dw::util::Values

fun lastNameMasked(lastName:String): String = lastName[0] ++ "****"
fun phoneNumnberMasked(phoneNumber:String): String = "(***)-(***)-"++ phoneNumber[-4 to -1]
fun emailMasked(email:String):String = "****@" ++ substringAfterLast(email,"@")
fun creditCardMasked(creditCard:String):String = "(****)-(****)-"++ creditCard[-4 to -1]
type currencyFormat = String {format: "₹ #,###.00"}

---

payload mask field("lastName") with lastNameMasked($)
mask field('firstName') with upper($)
mask field('phone') with phoneNumnberMasked($)
mask field('email') with emailMasked($)
mask field('creditCard') with creditCardMasked($)
mask field('salary') with $ as currencyFormat
Data weave playground snapshot

Exercise 7:

Given an array of transactions with amounts, categories, and payment methods, calculate the total amount spent for each category and payment method combination. Return an array of objects with category names, payment methods, and their total amounts.

Input

[
{
"amount": 50,
"category": "Groceries",
"paymentMethod": "Credit Card"
},
{
"amount": 75,
"category": "Electronics",
"paymentMethod": "Cash"
},
{
"amount": 30,
"category": "Groceries",
"paymentMethod": "Credit Card"
},
{
"amount": 40,
"category": "Electronics",
"paymentMethod": "Credit Card"
},
{
"amount": 20,
"category": "Clothing",
"paymentMethod": "Cash"
}
]

Output

[
{
"category": "Groceries",
"paymentMethod": "Credit Card",
"amout": 80
},
{
"category": "Electronics",
"paymentMethod": "Cash",
"amout": 75
},
{
"category": "Electronics",
"paymentMethod": "Credit Card",
"amout": 40
},
{
"category": "Clothing",
"paymentMethod": "Cash",
"amout": 20
}
]

Solution

%dw 2.0
output application/json
import * from dw::core::Arrays

---
payload map ((item, index) ->{
"category": item.category,
"paymentMethod": item.paymentMethod,
"amout": (payload filter ((itemFilter, indexFilter) -> (itemFilter.paymentMethod == item.paymentMethod) and (itemFilter.category == item.category) )) sumBy ((param_1) ->param_1.amount )

} ) distinctBy ((itemDistinct, indexDistinct) -> (itemDistinct.category as String ) ++ (itemDistinct.paymentMethod as String ))
Data weave playground snapshot

Exercise 8:

Given an array of orders with products, quantities, and unit prices, calculate the total cost for each product across all orders. Return an array of objects with product names and their total cost.

Input

[
{
"product": "Widget",
"quantity": 3,
"price": 25
},
{
"product": "Gadget",
"quantity": 3,
"price": 15
},
{
"product": "Doodad",
"quantity": 1,
"price": 30
},
{
"product": "Widget",
"quantity": 1,
"price": 25
}
]

Output

[
{
"product": "Widget",
"totalCost": 100
},
{
"product": "Gadget",
"totalCost": 45
},
{
"product": "Doodad",
"totalCost": 30
}
]

Solution

%dw 2.0
output application/json
import * from dw::core::Arrays

var calculatedCost = payload map ((itemOuterMap, indexOuterMap) -> {
"product": itemOuterMap.product,
"totalCost": (itemOuterMap.price * itemOuterMap.quantity)
} )

---
calculatedCost map ((itemMap, indexMap) -> {
"product": itemMap.product,
"totalCost": sumBy(calculatedCost filter ((itemFilter, indexFilter) -> itemFilter.product == itemMap.product ), (itemSum) -> itemSum.totalCost)
} ) distinctBy ((itemDistinct, indexDistinct) -> itemDistinct.product)
Data weave playground snapshot

Exercise 9:

Given an array of employees with salaries and department names, find the highest-paid employee in each department. Return an array of objects with employee names, their salary, and the department they work in.

Input

[
{
"name": "Alice",
"salary": 60000,
"department": "IT"
},
{
"name": "Bob",
"salary": 75000,
"department": "Finance"
},
{
"name": "Charlie",
"salary": 70000,
"department": "IT"
},
{
"name": "David",
"salary": 80000,
"department": "Finance"
}
]

Output

[
{
"name": "Charlie",
"department": "IT",
"salary": 70000
},
{
"name": "David",
"department": "Finance",
"salary": 80000
}
]

Solution

%dw 2.0
output application/json
import * from dw::core::Arrays

var groupedData = (payload orderBy ((itemOrder, indexOrder) -> itemOrder.salary )) groupBy ((itemGroup, indexGroup) -> itemGroup.department )

---
groupedData pluck ((value, key, index) ->{
"name": (value.name distinctBy $)[-1],
"department": (value.department distinctBy $)[0],
"salary": max(value.salary)
} )
Data weave playground snapshot

Exercise 10:

Given an array of students with subjects, grades, and teacher feedback, find the subject for each student where they received the highest grade. Return an array of objects with student names, the subject they excelled in, and the corresponding feedback.

Input

[
{
"name": "Alice",
"grades": {
"Math": 90,
"English": 85,
"History": 92
},
"feedback": {
"Math": "Great work!",
"English": "Good effort",
"History": "Outstanding"
}
},
{
"name": "Bob",
"grades": {
"Math": 75,
"English": 80,
"History": 88
},
"feedback": {
"Math": "Needs improvement",
"English": "Excellent",
"History": "Impressive"
}
},
{
"name": "Charlie",
"grades": {
"Math": 60,
"English": 70,
"History": 65
},
"feedback": {
"Math": "Well done",
"English": "Outstanding",
"History": "Average"
}
}
]

Output

[
{
"name": "Alice",
"subject": "History",
"feedback": "Outstanding"
},
{
"name": "Bob",
"subject": "History",
"feedback": "Impressive"
},
{
"name": "Charlie",
"subject": "English",
"feedback": "Outstanding"
}
]

Solution

%dw 2.0
output application/json
import * from dw::core::Arrays


---
payload map ((itemStudent, indexStudent) -> {
"name": itemStudent.name,
"Subject": keysOf(itemStudent.grades orderBy ((value, key) -> -value ))[0],
"feedback" : valuesOf((itemStudent.feedback filterObject ((value, key, index) ->
(key == keysOf(itemStudent.grades orderBy ((value, key) -> -value ))[0]))))[0]
})
Data weave playground snapshot

Exercise 11:

Given an array of orders with quantities and unit prices, calculate the total revenue for each order and format the results as an array of objects.

Input

[
{
"orderID": "A123",
"items": [
{
"name": "Product1",
"quantity": 2,
"price": 25
},
{
"name": "Product2",
"quantity": 3,
"price": 15
}
]
},
{
"orderID": "B456",
"items": [
{
"name": "Product3",
"quantity": 1,
"price": 50
},
{
"name": "Product4",
"quantity": 2,
"price": 10
}
]
}
]

Output

[
{
"orderID": "A123",
"totalRevenue": 95
},
{
"orderID": "B456",
"totalRevenue": 70
}
]

Solution

%dw 2.0
output application/json
import * from dw::core::Arrays

---
payload map ((itemOuterMap, indexOuterMap) -> {
"orderID": itemOuterMap.orderID,
"totalRevenue": itemOuterMap.items map ((itemInnerMap, indexInnerMap) ->{
"totalRevenue": (itemInnerMap.price * itemInnerMap.quantity)
} ) sumBy ((param_1) -> param_1.totalRevenue)
} )
Data weave playground snapshot

--

--

Rajeev Ranjan

Proficient in utilizing leading integration platforms, such as MuleSoft and TIBCO, to architect robust solutions.