RxJS - Transformation Operator groupBy



In groupBy operator, the output is grouped based on a specific condition and these group items are emitted as GroupedObservable.

Syntax

groupBy(keySelector_func: (value: T) => K):GroupedObservables

Parameters

keySelector_func − A function that gives the key for each item from the source observable.

Return value

The return value is an Observable that emits values as a GroupedObservables.

Example

import { of , from} from 'rxjs';
import { groupBy } from 'rxjs/operators';

const data = [
   {groupId: "QA", value: 1},
   {groupId: "Development", value: 3},
   {groupId: "QA", value: 5},
   {groupId: "Development", value: 6},
   {groupId: "QA", value: 2},
];

from(data).pipe(
   groupBy(item => item.groupId)
)
.subscribe(x => console.log(x));

If you see the output, it is an observable wherein the items are grouped. The data we have given has 2 groups QA and Development. The output shows the grouping of the same as shown below −

Output

groupBy Operator
Advertisements