Skip to content

Instantly share code, notes, and snippets.

@forivall
Created June 29, 2024 02:45
Show Gist options
  • Save forivall/587743583df3acecb0097463e35fd409 to your computer and use it in GitHub Desktop.
Save forivall/587743583df3acecb0097463e35fd409 to your computer and use it in GitHub Desktop.
Map.groupBy minimal ponyfill
/* This is equivalent to Map.groupBy; replace this function with Map.groupBy in Node 21+ */
function mapGroupBy<T, K>(array: T[], iteratee: (value: T, index: number, array: T[]) => K) {
return array.reduce((result, value, index, array) => {
const key = iteratee(value, index, array);
const group = result.get(key);
if (group) {
group.push(value);
} else {
result.set(key, [value]);
}
return result;
}, new Map<K, T[]>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment