group-by
Groups the elements of an array based on the result of a callback function. Creates an object where each key represents a group and the value is an array of items that belong to that group. The grouping is determined by the callback function which is applied to each element.
Installation
npx fragmen add array/group-bySource Code
/**
* Groups the elements of an array based on the result of a callback function.
*
* Creates an object where each key represents a group and the value is an array
* of items that belong to that group. The grouping is determined by the callback
* function which is applied to each element.
*
* @tags pure, array-manipulation
* @param {T[]} array The array of elements to group.
* @param {(item: T) => string} getKey Function that takes an item and returns the key for grouping.
* @returns {Record<K, T[]>} An object where keys are group identifiers and values are arrays of grouped items.
*
* @example
* ```typescript
* const numbers = [1, 2, 3, 4, 5, 6];
* const grouped = groupBy(numbers, n => n % 2 === 0 ? 'even' : 'odd');
* // Result: { odd: [1, 3, 5], even: [2, 4, 6] }
*
* const users = [
* { name: 'Alice', department: 'Engineering' },
* { name: 'Bob', department: 'Marketing' },
* { name: 'Charlie', department: 'Engineering' }
* ];
* const byDepartment = groupBy(users, user => user.department);
* // Result: { Engineering: [Alice, Charlie], Marketing: [Bob] }
* ```
*/
export function groupBy<T, K extends string | number | symbol>(
array: T[],
getKey: (item: T) => K
): Record<K, T[]> {
return array.reduce(
(acc, item) => {
const key = getKey(item);
if (!(key in acc)) {
acc[key] = [];
}
acc[key].push(item);
return acc;
},
{} as Record<K, T[]>
);
}
Examples
const numbers = [1, 2, 3, 4, 5, 6];
const grouped = groupBy(numbers, n => n % 2 === 0 ? 'even' : 'odd');
// Result: { odd: [1, 3, 5], even: [2, 4, 6] }
const users = [
{ name: 'Alice', department: 'Engineering' },
{ name: 'Bob', department: 'Marketing' },
{ name: 'Charlie', department: 'Engineering' }
];
const byDepartment = groupBy(users, user => user.department);
// Result: { Engineering: [Alice, Charlie], Marketing: [Bob] }
Related Utilities
chunk
arraySplits an array into chunks of a specified size. Creates a new array containing subarrays (chunks) of the original array, each with a maximum length of the specified size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size.
compact
arrayRemoves falsy values from an array. Creates a new array with all falsy values removed. Falsy values are: false, null, 0, "", undefined, and NaN. This is useful for cleaning arrays and ensuring only truthy values remain.
difference
arrayCreates an array of values from the first array that are not present in the other arrays. Returns a new array containing elements that exist in the first array but not in any of the subsequent arrays. The order of elements follows the order of the first array. Duplicates in the first array are preserved unless they appear in other arrays.
flatten
arrayFlattens nested arrays to a specified depth. Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. A depth of 1 flattens only the first level of nesting, while Infinity flattens all levels.
intersection
arrayFinds the intersection of two or more arrays. Returns a new array containing only the elements that are present in all provided arrays. The order of elements in the result follows the order of the first array. Duplicates are removed from the result.
sort-by
arraySorts an array of objects by a property or using a custom function. Creates a new sorted array without mutating the original. Can sort by a property name (for objects) or by using a custom iteratee function. Supports ascending and descending order.
Quick Actions
Tags
Parameters
arrayT[]The array of elements to group.
getKey(item: T) => stringFunction that takes an item and returns the key for grouping.
Returns
Record<K, T[]>An object where keys are group identifiers and values are arrays of grouped items.