groupBy
deprecateduse the options parameter instead.
§Return Type
§Return Type
§Return Type
§Parameters
§Return Type
§Parameters
§Return Type
Groups the items emitted by an Observable according to a specified criterion,
and emits these grouped items as GroupedObservables
, one
GroupedObservable per group.
When the Observable emits an item, a key is computed for this item with the key function.
If a GroupedObservable for this key exists, this GroupedObservable emits. Otherwise, a new GroupedObservable for this key is created and emits.
A GroupedObservable represents values belonging to the same group represented by a common key. The common
key is available as the key
field of a GroupedObservable instance.
The elements emitted by GroupedObservables are by default the items emitted by the Observable, or elements returned by the element function.
Examples
Group objects by id
and return as array
import { of, groupBy, mergeMap, reduce } from 'rxjs';
of(
{ id: 1, name: 'JavaScript' },
{ id: 2, name: 'Parcel' },
{ id: 2, name: 'webpack' },
{ id: 1, name: 'TypeScript' },
{ id: 3, name: 'TSLint' }
).pipe(
groupBy(p => p.id),
mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [])))
)
.subscribe(p => console.log(p));
// displays:
// [{ id: 1, name: 'JavaScript' }, { id: 1, name: 'TypeScript'}]
// [{ id: 2, name: 'Parcel' }, { id: 2, name: 'webpack'}]
// [{ id: 3, name: 'TSLint' }]
Pivot data on the id
field
import { of, groupBy, mergeMap, reduce, map } from 'rxjs';
of(
{ id: 1, name: 'JavaScript' },
{ id: 2, name: 'Parcel' },
{ id: 2, name: 'webpack' },
{ id: 1, name: 'TypeScript' },
{ id: 3, name: 'TSLint' }
).pipe(
groupBy(p => p.id, { element: p => p.name }),
mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [`${ group$.key }`]))),
map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))
)
.subscribe(p => console.log(p));
// displays:
// { id: 1, values: [ 'JavaScript', 'TypeScript' ] }
// { id: 2, values: [ 'Parcel', 'webpack' ] }
// { id: 3, values: [ 'TSLint' ] }
§Parameters
A function that returns an Observable to determine how long each group should exist.
§Return Type
A function that returns an Observable that emits GroupedObservables, each of which corresponds to a unique key value and each of which emits those items from the source Observable that share that key value.