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

    Function countBy

    • Counts the occurrences of elements grouped by a derived key.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      • TKey

        Type produced by keySelector.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • keySelector: Selector<TElement, TKey>

        Selector used to derive the grouping key for each element.

      • Optionalcomparator: EqualityComparator<TKey, TKey>

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

      Returns IEnumerable<KeyValuePair<TKey, number>>

      A sequence of key/count pairs describing how many elements share each key.

      Each key appears exactly once in the result with its associated occurrence count.

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

      const countByCategory = countBy(products, p => p.category).toArray();
      console.log(countByCategory);
      // [
      // { key: 'Fruit', value: 2 },
      // { key: 'Vegetable', value: 1 }
      // ]