TS-Scribe - v0.6.2
    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.

      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' }] }