Skip to content

Instantly share code, notes, and snippets.

@alex-taxiera
Created June 19, 2020 02:57
Show Gist options
  • Save alex-taxiera/0618c35ff27a32e81fc9866d8e376658 to your computer and use it in GitHub Desktop.
Save alex-taxiera/0618c35ff27a32e81fc9866d8e376658 to your computer and use it in GitHub Desktop.
group by function to replace lodash groupBy
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