Skip to content

Function: groupBy()

groupBy<T, K>(keySelector): Operator<T, GroupItem<T, K>>

Defined in: operators/groupBy.ts:31

Creates a stream operator that groups values from the source stream by a computed key.

This operator is a projection operator that transforms a stream of values into a stream of GroupItem objects. For each value from the source, it applies the keySelector function to determine a key and then emits an object containing both the original value and the computed key.

This operator is the first step in a typical grouping pipeline. The resulting stream of GroupItem objects can then be processed further by other operators (e.g., scan or reduce) to perform a true grouping into collections.

Type Parameters

T

T = any

The type of the values in the source stream.

K

K = any

The type of the key computed by keySelector.

Parameters

keySelector

(value) => CallbackReturnType<K>

A function that takes a value from the source stream and returns a key. This function can be synchronous or asynchronous.

Returns

Operator<T, GroupItem<T, K>>

An Operator instance that can be used in a stream's pipe method.

Examples

From groupBy.spec.ts:4

typescript
let result: any[] = [];
const groupsMap = new Map<string, any[]>();
from([1, 2, 3, 4, 5, 6])
  .pipe(groupBy((value: number) => (value % 2 === 0 ? 'even' : 'odd')))
  .subscribe({
    next: (groupItem) => {
      // Update the latest group with just the emitted value
      const groupValues = groupsMap.get(groupItem.key) || [];
      groupValues.push(groupItem.value); // Add the current value to the group
      groupsMap.set(groupItem.key, groupValues); // Update the group values
    },
    complete: () => {
      // Ensure 'odd' group comes first
      const sortedGroups = ['odd', 'even'].flatMap(
        (key) => groupsMap.get(key) ?? []
      );

      result = sortedGroups;
      expect(result).toEqual([1, 3, 5, 2, 4, 6]); // Odd numbers first, then even
      done();
    },
  });

Released under the MIT License.