Created
March 23, 2021 01:13
-
-
Save elib0/8b95d156ff4710fb3c65ae15a54f6f03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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