Created
June 19, 2020 02:57
-
-
Save alex-taxiera/0618c35ff27a32e81fc9866d8e376658 to your computer and use it in GitHub Desktop.
group by function to replace lodash groupBy
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
function groupBy <T = unknown> ( | |
list: Array<T>, | |
keyGen: (item: T) => string | number, | |
): {[k: string]: Array<T>} { | |
return list.reduce<{[k: string]: Array<T>}>((ax, dx) => { | |
const key = keyGen(dx) | |
if (ax[key]) { | |
ax[key].push(dx) | |
} else { | |
ax[key] = [ dx ] | |
} | |
return ax | |
}, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment