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
.
[1,2,3,4,5,6,7,8,9,10]
%dw 2.0
output json
---
payload groupBy (n, idx) -> isEven(n)
{
"false": [
1,3,5,7,9
],
"true": [
2,4,6,8,10
]
}
[
{
"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 2.0
output json
---
payload groupBy (n, idx) -> n.dayOfWeek
{
"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"
}
]
}
If you like my post please follow me to read my latest post on programming and technology.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…