Tweakr
    Preparing search index...

    Function groupBy

    • Groups elements of an array by a key derived from each element.

      The grouping key can be returned from a callback function. Handles undefined and null keys safely by grouping them under "__undefined__".

      Type Parameters

      • T
      • K extends string | number | symbol

      Parameters

      • array: T[]

        The array to group.

      • keyFn: (item: T) => undefined | null | K

        A function that returns the key used for grouping.

      Returns Record<string, T[]>

      An object where keys represent group identifiers and values are arrays of grouped elements.

      groupBy(
      [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "a" }],
      (item) => item.type
      );
      // → { a: [{ id: 1, type: "a" }, { id: 3, type: "a" }], b: [{ id: 2, type: "b" }] }

      groupBy([1, 2, null, 3], (n) => (n ?? "missing").toString());
      // → { "1": [1], "2": [2], "missing": [null], "3": [3] }

      1.2.0