import isUnsafeKey from '../object/isUnsafeKey'; import isFunction from '../types/isFunction'; /** * Creates an object composed of keys generated from the results of running each element of collection through iteratee. * * Keys of `__proto__`, `constructor` and `prototype` are refused and their * elements dropped, as writing one would reach the prototype of the result. * * @param {T[]} arr The source array. * @param {Function|string} key The iteratee to transform keys. * @returns {Record} The composed aggregate object. * * @example * groupBy([6.1, 4.2, 6.3], Math.floor) //=> { '4': [4.2], '6': [6.1, 6.3] } */ export default function groupBy( arr: T[], key: ((val: T, index: number, arr: T[]) => string) | string, ): Record { return arr.reduce((acc: Record, obj, index, array) => { const k = String( isFunction(key) ? key(obj, index, array) : obj[key as keyof T], ); if (isUnsafeKey(k)) { return acc; } if (!acc[k]) { acc[k] = []; } acc[k].push(obj); return acc; }, {}); }