Skip to main content

groupBy

/**
* Creates an object composed of keys generated
* from iteratee results and values containing
* arrays of the original elements.
*
* Time Complexity:
* O(n)
*
* Space Complexity:
* O(n)
*
* @param {Array} array
* @param {(value: any) => any} iteratee
* @returns {Object}
*/
export default function groupBy(array, iteratee) {
const result = {};

for (const item of array) {
// Generate grouping key
const key = iteratee(item);

// Initialize bucket if missing
if (!(key in result)) {
result[key] = [];
}

// Store original item
result[key].push(item);
}

return result;
}

/**
groupBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': [4.2], '6': [6.1, 6.3] }

groupBy([{ n: 3 }, { n: 5 }, { n: 3 }], (o) => o.n);
// => { '3': [{ n: 3 }, { n: 3 }], '5': [{ n: 5 }] }

groupBy([], (o) => o); // => {}

groupBy([{ n: 1 }, { n: 2 }], (o) => o.m); // => { undefined: [{ n: 1 }, { n: 2 }] }
*/