Group By
Groups the elements of an array based on a provided key-generating function.
Category | Arrays |
Author | Pol Gubau |
Since | 1.0.0 |
Last Updated | 2025-03-15 |
Type | Sync |
Compatibility | Universal |
Example
Input
groupBy([ {category: 'fruit', name: 'apple'}, {category: 'fruit', name: 'banana'}, {category: 'vegetable', name: 'carrot'} ], item => item.category)
Output:
{ fruit: [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }], vegetable: [{category: 'vegetable', name: 'carrot' }] }
Return
An object where each key is associated with an array of elements that share that key.
Type: Record<K, T[]>
Props
Name | Type | Default | Required | Description |
---|---|---|---|---|
arr | T[] | null | Yes | The array to be grouped. |
getKeyFromItem | (item: T) => K | null | Yes | A function that generates a key from an element. |
Notes
Keys must be a valid property key (string, number, or symbol).
Tags
- array
- grouping
- object