UNPKG

typedash

Version:

modern, type-safe collection of utility functions

45 lines (43 loc) 1.04 kB
//#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 Object.defineProperty(exports, 'groupBy', { enumerable: true, get: function () { return groupBy; } }); //# sourceMappingURL=groupBy-CTfqrrae.cjs.map