UNPKG

typedash

Version:

modern, type-safe collection of utility functions

39 lines (38 loc) 953 B
//#region src/functions/groupBy/groupBy.ts /** * Takes an array and returns an object with the keys of the array mapped to the items of the array. * @param array The array to iterate over. * @param getter The function used to extract the key from each element. * @returns An object with the keys mapped to the elements. * @example * ```ts * groupBy( * [ * { id: 'a', value: 1 }, * { id: 'b', value: 1 }, * { id: 'c', value: 2 }, * ], * (item) => item.value * ) * // { * // 1: [ * // { id: 'a', value: 1 }, * // { id: 'b', value: 1 }, * // ], * // 2: [ * // { id: 'c', value: 2 }, * // ], * // } * ``` */ function groupBy(array, getter) { return (array ?? []).reduce((draftGroups, currentItem) => { const key = getter(currentItem); draftGroups[key] ??= []; draftGroups[key].push(currentItem); return draftGroups; }, {}); } //#endregion export { groupBy as t }; //# sourceMappingURL=groupBy-BzePjVoX.js.map