TS-Scribe - v1.2.0
    Preparing search index...

    Function arrayGroupBy

    • Groups the elements of an array by a specified key generated from each element.

      This function iterates over the provided array and uses a key-generating function (keyFunc) to determine the key for each element. The result is an object where each key is associated with an array of elements that share the same key.

      Type Parameters

      • T

      Parameters

      • array: T[]

        The array to group.

      • keyFunc: ArrayGroupByKeyFn<T>

        The function to generate a key for each element.

      Returns Record<string | number, T[]>

      An object where keys are generated by keyFunc and the values are arrays of elements that share the same key.

      A native equivalent, Object.groupBy, is available in ES2024+ (Node.js ≥ 21, all modern browsers). Prefer the built-in when targeting those environments:

      const grouped = Object.groupBy(arr, (item) => item.id);
      

      arrayGroupBy is useful for older targets or when a plain Record<string | number, T[]> return type is preferred over the Partial<Record<K, T[]>> that Object.groupBy returns.

      const arr = [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
      { id: 1, name: 'Charlie' },
      ];
      const grouped = arrayGroupBy(arr, (item) => item.id);
      console.log(grouped);
      // Output: { 1: [{ id: 1, name: 'Alice' }, { id: 1, name: 'Charlie' }], 2: [{ id: 2, name: 'Bob' }] }