• groupBy
    • 签名: groupBy(keySelector: Function, elementSelector: Function): Observable
  • 基于提供的值分组成多个 observables
    • 示例
      • 示例 1: 根据属性分组
  • 其他资源

    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));

    其他资源

    • groupBy :newspaper: - 官方文档
    • 使用 RxJS 的 groupBy 操作符分组成高阶 observables :video_camera: :dollar: - André Staltz
    • 在真实的 RxJS 应用中使用 groupBy :video_camera: :dollar: - André Staltz

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