RxJS groupBy() Transformation OperatorRxJS 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
Return valueThe 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' ] ]
Next TopicRxJS Operators
|