The groupBy function takes a list of objects [x1,…,xn] and some function f.It will then map f on the list, giving the list of objects [f(x1),…,f(xn)], and use these values to perform the groupBy operation. This function is useful for grouping together items in an array based on some value that is generated from each item in the array.
groupBy(Array<T>, ((T, Number) -> R)): Object<(R), Array<T>>
groupBy
is different from the other functions we’ve covered in this tutorial because groupBy
does not return an Array
, it returns an Object
. When we define Object
types, we can use two type parameters:
Object<(R), Array<T>>
The first type parameter is the type of the keys, and the second type parameter is the type of the values. Applying this to groupBy
, we can see it returns an Object
whose keys are the type of the values returned from the lambda, and the values are the type of the input Array
.
Input
[1,2,3,4,5,6,7,8,9,10]
DW Script
%dw 2.0
output json
---
payload groupBy (n, idx) -> isEven(n)
Output
{
"false": [
1,3,5,7,9
],
"true": [
2,4,6,8,10
]
}
Input
[
{
"datetime": "2020-01-01T08:00:00",
"dayOfWeek": "wed",
"event": "Breakfast @ Cafe"
},
{
"datetime": "2020-01-01T18:00:00",
"dayOfWeek": "wed",
"event": "Study for cert exam"
},
{
"datetime": "2020-01-04T16:00:00",
"dayOfWeek": "sat",
"event": "Drinks w/ friends"
},
{
"datetime": "2020-01-08T08:00:00",
"dayOfWeek": "wed",
"event": "Develop mule application"
},
{
"datetime": "2020-01-05T08:00:00",
"dayOfWeek": "sun",
"event": "Football game"
}
]
DW Script
%dw 2.0
output json
---
payload groupBy (n, idx) -> n.dayOfWeek
Output
{
"wed": [
{
"datetime": "2020-01-01T08:00:00",
"dayOfWeek": "wed",
"event": "Breakfast @ Cafe"
},
{
"datetime": "2020-01-01T18:00:00",
"dayOfWeek": "wed",
"event": "Study for cert exam"
},
{
"datetime": "2020-01-08T08:00:00",
"dayOfWeek": "wed",
"event": "Develop mule application"
}
],
"sat": [
{
"datetime": "2020-01-04T16:00:00",
"dayOfWeek": "sat",
"event": "Drinks w/ friends"
}
],
"sun": [
{
"datetime": "2020-01-05T08:00:00",
"dayOfWeek": "sun",
"event": "Football game"
}
]
}
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
Leave a Comment