RxJS groupBy() Transformation Operator
RxJS groupBy() operator is a transformation operator that takes values emitted by the source Observable and then group them according to the criteria you set for them. It emits these grouped items as GroupedObservables, one GroupedObservable per group.
It takes 4 arguments as keySelector, elementSelector, durationSelector, and subjectSelector.
Syntax:
Following is the syntax of the groupBy() operator:
More precisely, we can write it as:
Parameter Explanation
- keySelector_func: It specifies a function that gives the key for each item from the source observable.
- keySelector: The keySelector is a function that extracts the key for each item.
- elementSelector: The elementSelector is a function that extracts the return element for each item. It is an optional argument. Its default value is undefined.
- durationSelector: The durationSelector is a function that returns an Observable to determine how long each group should exist. It is also an optional argument. Its default value is undefined.
- subjectSelector: The subjectSelector is a function that returns a Subject. For example, we can use it as follows: Type: () => Subject. It is also an optional argument. Its default value is undefined.
Return value
The groupBy() operator’s return value is observable that emits values as a GroupedObservables, where each of them corresponds to a unique key value.
Let us see some examples of groupBy() operator to understand it clearly.
Example 1 (Group by property)
Output:
After executing the above example, you will see the following result as array:
[ { name: 'Alex', age: 31 } ] [ { name: 'Adam', age: 28 } ] [ { name: 'Alia', age: 21 } ] [ { name: 'David', age: 35 } ]
In the above example, you can see that we have used age property to groupby the values and fetch them.
Example 2 (Group objects by id and return them as an array)
Output:
After executing the above example, you will see the following result:
[ { course_id: 1, name: 'Java' }, { course_id: 1, name: 'Python' } ] [ { course_id: 2, name: 'Vue.js' }, { course_id: 2, name: 'AngularJS' } ] [ { course_id: 3, name: 'PHP' } ]
Example 3 (Group by into key – values)
Output:
[ 31, [ 'Alex', 'Samson' ] ] [ 28, [ 'Adam', 'Rhea' ] ] [ 21, [ 'Alia' ] ] [ 35, [ 'David', 'Dhoni' ] ]