groupBy

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

Group into observables based on provided value.

groupBy - 图1

Examples

Example 1: Group by property

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { groupBy, mergeMap, toArray } from 'rxjs/operators';
  3. const people = [
  4. { name: 'Sue', age: 25 },
  5. { name: 'Joe', age: 30 },
  6. { name: 'Frank', age: 25 },
  7. { name: 'Sarah', age: 35 }
  8. ];
  9. //emit each person
  10. const source = from(people);
  11. //group by age
  12. const example = source.pipe(
  13. groupBy(person => person.age),
  14. // return each item in group as array
  15. mergeMap(group => group.pipe(toArray()))
  16. );
  17. /*
  18. output:
  19. [{age: 25, name: "Sue"},{age: 25, name: "Frank"}]
  20. [{age: 30, name: "Joe"}]
  21. [{age: 35, name: "Sarah"}]
  22. */
  23. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/groupBy.ts