@tremendous/help
    Preparing search index...

    Function groupBy

    • Groups the elements of an array based on a specified key extractor function.

      This function takes an array and a function that extracts a key from each element, and returns an object where the keys are the extracted values and the values are arrays of elements that correspond to each key.

      Type Parameters

      • ArrayElement = unknown

        The type of the elements in the array.

      • ExtractedValue extends string | number | symbol = string

        The type of the keys extracted from the elements.

      Parameters

      Returns Record<ExtractedValue, ArrayElement[]>

      • The grouped elements as an object.
      const array = [
      { category: 'fruit', name: 'apple' },
      { category: 'fruit', name: 'banana' },
      { category: 'vegetable', name: 'carrot' }
      ];
      const grouped = groupBy(array, x => x.category);
      // grouped will be {
      // fruit: [{ category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }],
      // vegetable: [{ category: 'vegetable', name: 'carrot' }]
      // }