Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active March 4, 2020 23:17
Show Gist options
  • Save VitorLuizC/2baa4e96f42e6436c1f622d537ee2ffa to your computer and use it in GitHub Desktop.
Save VitorLuizC/2baa4e96f42e6436c1f622d537ee2ffa to your computer and use it in GitHub Desktop.
A groupBy function in TypeScript.
function groupBy(fn) {
return function(items) {
return items.reduce(function(groups, item) {
var key = fn(item);
if (!(key in groups))
// eslint-disable-next-line no-param-reassign
groups[key] = [];
groups[key].push(item);
return groups;
}, Object.create(null));
};
}
export default groupBy;
const groupBy = <T, K extends string>(fn: (item: T) => K) => (items: T[]) =>
items.reduce((groups, item) => {
const key = fn(item);
return {
...groups,
[key]: [...(groups?.[key] ?? []), item]
};
}, {} as Record<K, T[]>);
export default groupBy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment