Skip to main content

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

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/groupBy6,982,132.030.0001fastest
lodash/groupBy4,223,901.690.0002slowest
  • modern-kit/groupBy
    • 1.65x faster 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' },
// ],
// };

References