groupBy
Groups an array based on a given criterion.
An iteratee function is provided to group items by the returned key. Each key is assigned as a property of the resulting object containing an array of grouped items.
Code
Benchmark
hz: Operations per secondmean: Average response time (ms)
| Name | hz | mean | Performance |
|---|---|---|---|
| modern-kit/groupBy | 6,982,132.03 | 0.0001 | fastest |
| lodash/groupBy | 4,223,901.69 | 0.0002 | slowest |
- modern-kit/groupBy
1.65xfaster than lodash/groupBy
Interface
typescript
function groupBy<T, K extends PropertyKey>(
arr: T[] | readonly T[],
iteratee: (item: T) => K
): Record<K, T[]>;
Usage
typescript
import { groupBy } from '@modern-kit/utils';
const items = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'vegetable', name: 'carrot' },
{ category: 'fruit', name: 'pear' },
{ category: 'vegetable', name: 'broccoli' },
];
const group = groupBy(items, (item) => item.category);
// {
// fruit: [
// { category: 'fruit', name: 'apple' },
// { category: 'fruit', name: 'banana' },
// { category: 'fruit', name: 'pear' },
// ],
// vegetable: [
// { category: 'vegetable', name: 'carrot' },
// { category: 'vegetable', name: 'broccoli' },
// ],
// };