@mirei/ts-collections
    Preparing search index...

    Function groupBy

    • Partitions the sequence into groups based on keys projected from each element.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      • TKey

        Type of key produced by keySelector.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • keySelector: Selector<TElement, TKey>

        Selector used to derive the grouping key for each element.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to match keys. Defaults to the library's standard equality comparison.

      Returns IEnumerable<IGroup<TKey, TElement>>

      A sequence of groups, each exposing the key and the elements that share it.

      The source sequence is enumerated once when the result is iterated. Elements within each group preserve their original order, and group contents are cached for repeated enumeration.

      const products = [
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      ];

      const grouped = groupBy(products, p => p.category);
      for (const group of grouped) {
      console.log(group.key, group.toArray());
      }
      // Fruit [ { name: 'Apple', category: 'Fruit' }, { name: 'Banana', category: 'Fruit' } ]
      // Vegetable [ { name: 'Carrot', category: 'Vegetable' } ]