UNPKG

es-next-tools

Version:

A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.

26 lines (25 loc) 905 B
/** * Groups the elements in the array according to the specified key function. * @param {T[]} array - The array to group. * @param {Function} fn - The function to determine the grouping key for each element. * @returns {Record<K, T[]>} An object where keys are the group names and values are arrays of grouped elements. * @template T, K * @deprecated - Use Object.groupBy() instead. * @example * const people = [ * { name: 'Alice', age: 30 }, * { name: 'Bob', age: 25 }, * { name: 'Charlie', age: 30 } * ]; * const grouped = groupBy(people, person => person.age); * // { '25': [{ name: 'Bob', age: 25 }], '30': [{ name: 'Alice', age: 30 }, { name: 'Charlie', age: 30 }] } */ export function groupBy(array, fn) { return array.reduce((acc, item) => { const key = fn(item); acc[key] = acc[key] || []; acc[key].push(item); return acc; }, {}); } ;