@rxap/utilities
Version:
A collection of utility functions, types and interfaces.
26 lines • 1.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroupBy = GroupBy;
/**
* Groups elements of an array based on a specified property or function.
*
* @template T - The type of the elements in the array.
* @template K - The type of the property key.
* @template MK - The type of the grouping key.
*
* @param {T[]} list - The array of items to be grouped.
* @param {K | ((item: T) => MK)} propertyKeyOrFunction - A property key or a function to determine the grouping key for each item.
* @return {Map<MK, T[]>} A map where keys are the grouping key, and values are arrays of grouped items.
*/
function GroupBy(list, propertyKeyOrFunction) {
const map = new Map();
for (const item of list) {
const key = typeof propertyKeyOrFunction === 'function' ? propertyKeyOrFunction(item) : item[propertyKeyOrFunction];
if (!map.has(key)) {
map.set(key, []);
}
map.get(key).push(item);
}
return map;
}
//# sourceMappingURL=group-by.js.map