groupBy

签名: groupBy(keySelector: Function, elementSelector: Function): Observable

基于提供的值分组成多个 observables

groupBy - 图1

示例

示例 1: 根据属性分组

( 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. // 发出每个 people
  10. const source = from(people);
  11. // 根据 age 分组
  12. const example = source.pipe(
  13. groupBy(person => person.age),
  14. // 为每个分组返回一个数组
  15. mergeMap(group => group.pipe(toArray()))
  16. );
  17. /*
  18. 输出:
  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));

其他资源


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