GROUP_BY

Groups an array of objects by a key or the result of a LAMBDA function. as_array is a boolean keyword argument (TRUE / FALSE, default FALSE). When as_array is TRUE, GROUP_BY returns an array of objects with key and values properties. When as_array is FALSE, it returns an object keyed by group.

Syntax 

GROUP_BY(items, key_or_lambda, [as_array: FALSE])

Usage examples 

Example 1

Input

1
{
2
"employees": [
3
{
4
"name": "Alice",
5
"office": "Dublin"
6
},
7
{
8
"name": "Bob",
9
"office": "Dublin"
10
},
11
{
12
"name": "Charlie",
13
"office": "New York"
14
},
15
{
16
"name": "Dave",
17
"office": "New York"
18
}
19
]
20
}

Formula

GROUP_BY(employees, "office")

Output

1
{
2
"Dublin": [
3
{
4
"name": "Alice",
5
"office": "Dublin"
6
},
7
{
8
"name": "Bob",
9
"office": "Dublin"
10
}
11
],
12
"New York": [
13
{
14
"name": "Charlie",
15
"office": "New York"
16
},
17
{
18
"name": "Dave",
19
"office": "New York"
20
}
21
]
22
}

Example 2

Input

1
{
2
"alerts": [
3
{
4
"name": "Failed Login",
5
"severity": 8,
6
"source": "firewall"
7
},
8
{
9
"name": "Config Change",
10
"severity": 5,
11
"source": "audit"
12
},
13
{
14
"name": "Disk Space Low",
15
"severity": 3,
16
"source": "monitoring"
17
},
18
{
19
"name": "Malware Detected",
20
"severity": 9,
21
"source": "endpoint"
22
}
23
]
24
}

Formula

GROUP_BY(alerts, LAMBDA(alert, IF(alert['severity'] > 7, 'high', IF(alert['severity'] > 4, 'medium', 'low'))))

Output

1
{
2
"high": [
3
{
4
"name": "Failed Login",
5
"severity": 8,
6
"source": "firewall"
7
},
8
{
9
"name": "Malware Detected",
10
"severity": 9,
11
"source": "endpoint"
12
}
13
],
14
"medium": [
15
{
16
"name": "Config Change",
17
"severity": 5,
18
"source": "audit"
19
}
20
],
21
"low": [
22
{
23
"name": "Disk Space Low",
24
"severity": 3,
25
"source": "monitoring"
26
}
27
]
28
}

Example 3

Input

1
{
2
"employees": [
3
{
4
"name": "Alice",
5
"office": "Dublin"
6
},
7
{
8
"name": "Bob",
9
"office": "Dublin"
10
},
11
{
12
"name": "Charlie",
13
"office": "New York"
14
},
15
{
16
"name": "Dave",
17
"office": "New York"
18
}
19
]
20
}

Formula

GROUP_BY(employees, 'office', as_array: TRUE)

Output

1
[
2
{
3
"key": "Dublin",
4
"values": [
5
{
6
"name": "Alice",
7
"office": "Dublin"
8
},
9
{
10
"name": "Bob",
11
"office": "Dublin"
12
}
13
]
14
},
15
{
16
"key": "New York",
17
"values": [
18
{
19
"name": "Charlie",
20
"office": "New York"
21
},
22
{
23
"name": "Dave",
24
"office": "New York"
25
}
26
]
27
}
28
]
Was this helpful?