2024-04-25 14:56:13 +03:00
|
|
|
# groupBy
|
|
|
|
|
|
|
|
Groups the elements of an array based on a provided key-generating function.
|
|
|
|
|
2024-06-04 11:19:26 +03:00
|
|
|
This function takes an array and a function that generates a key from each element. It returns
|
|
|
|
an object where the keys are the generated keys and the values are arrays of elements that share
|
2024-04-25 14:56:13 +03:00
|
|
|
the same key.
|
|
|
|
|
|
|
|
## Signature
|
|
|
|
|
|
|
|
```typescript
|
|
|
|
function groupBy<T, K extends string>(arr: T[], getKeyFromItem: (item: T) => K): Record<K, T[]>;
|
|
|
|
```
|
|
|
|
|
2024-06-04 11:19:26 +03:00
|
|
|
### Parameters
|
2024-04-25 14:56:13 +03:00
|
|
|
|
|
|
|
- `arr` (`T[]`): The array to group.
|
|
|
|
- `getKeyFromItem` (`(item: T) => K`): A function that generates a key from an element.
|
|
|
|
|
|
|
|
### Returns
|
|
|
|
|
2024-06-04 11:19:26 +03:00
|
|
|
(`Record<K, T[]>`) An object where each key is associated with an array of elements that
|
2024-04-25 14:56:13 +03:00
|
|
|
share that key.
|
|
|
|
|
|
|
|
## Examples
|
|
|
|
|
|
|
|
```typescript
|
|
|
|
const array = [
|
|
|
|
{ category: 'fruit', name: 'apple' },
|
|
|
|
{ category: 'fruit', name: 'banana' },
|
2024-06-04 11:19:26 +03:00
|
|
|
{ category: 'vegetable', name: 'carrot' },
|
2024-04-25 14:56:13 +03:00
|
|
|
];
|
|
|
|
const result = groupBy(array, item => item.category);
|
|
|
|
// result will be:
|
|
|
|
// {
|
|
|
|
// fruit: [
|
|
|
|
// { category: 'fruit', name: 'apple' },
|
|
|
|
// { category: 'fruit', name: 'banana' }
|
|
|
|
// ],
|
|
|
|
// vegetable: [
|
|
|
|
// { category: 'vegetable', name: 'carrot' }
|
|
|
|
// ]
|
|
|
|
// }
|
|
|
|
```
|