Skip to content

Instantly share code, notes, and snippets.

@elib0
Created March 23, 2021 01:13
Show Gist options
  • Save elib0/8b95d156ff4710fb3c65ae15a54f6f03 to your computer and use it in GitHub Desktop.
Save elib0/8b95d156ff4710fb3c65ae15a54f6f03 to your computer and use it in GitHub Desktop.
/**
* @description
* Takes an Array<V>, and a grouping function,
* and returns a Map of the array grouped by the grouping function.
*
* @param list An array of type V.
* @param keyGetter A Function that takes the the Array type V as an input, and returns a value of type K.
* K is generally intended to be a property key of V.
*
* @returns Map of the array grouped by the grouping function.
*/
//export function groupBy<K, V>(list: Array<V>, keyGetter: (input: V) => K): Map<K, Array<V>> {
// const map = new Map<K, Array<V>>();
function groupBy(list, keyGetter) {
const map = new Map();
list.forEach((item) => {
const key = keyGetter(item);
const collection = map.get(key);
if (!collection) {
map.set(key, [item]);
} else {
collection.push(item);
}
});
return map;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment