Learn RxJS
Search…
groupBy

signature: groupBy(keySelector: Function, elementSelector: Function): Observable

Group into observables based on provided value.

Examples

Example 1: Group by property
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { groupBy, mergeMap, toArray } from 'rxjs/operators';
4
5
const people = [
6
{ name: 'Sue', age: 25 },
7
{ name: 'Joe', age: 30 },
8
{ name: 'Frank', age: 25 },
9
{ name: 'Sarah', age: 35 }
10
];
11
//emit each person
12
const source = from(people);
13
//group by age
14
const example = source.pipe(
15
groupBy(person => person.age),
16
// return each item in group as array
17
mergeMap(group => group.pipe(toArray()))
18
);
19
/*
20
output:
21
[{age: 25, name: "Sue"},{age: 25, name: "Frank"}]
22
[{age: 30, name: "Joe"}]
23
[{age: 35, name: "Sarah"}]
24
*/
25
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Group by into key - values
1
// RxJS v6+
2
import { from, of, zip } from 'rxjs';
3
import { groupBy, mergeMap, toArray } from 'rxjs/operators';
4
5
const people = [
6
{ name: 'Sue', age: 25 },
7
{ name: 'Joe', age: 30 },
8
{ name: 'Frank', age: 25 },
9
{ name: 'Sarah', age: 35 }
10
];
11
12
from(people)
13
.pipe(
14
groupBy(
15
person => person.age,
16
p => p.name
17
),
18
mergeMap(group => zip(of(group.key), group.pipe(toArray())))
19
)
20
.subscribe(console.log);
21
22
/*
23
output:
24
[25, ["Sue", "Frank"]]
25
[30, ["Joe"]]
26
[35, ["Sarah"]]
27
*/
Copied!

Additional Resources

Last modified 1yr ago