Skip to content

Instantly share code, notes, and snippets.

@sergeyt
Last active July 14, 2016 07:02
Show Gist options
  • Save sergeyt/18ce409a63a44cb4c4923d04d8571f56 to your computer and use it in GitHub Desktop.
Save sergeyt/18ce409a63a44cb4c4923d04d8571f56 to your computer and use it in GitHub Desktop.
interface Group<TKey, TValue> {
key: TKey;
values: TValue[];
}
function groupBy<TKey, TValue>(array: TValue[], keyFn: (t: TValue) => TKey): Group<TKey,TValue>[] {
const result: Group<TKey, TValue>[] = [];
const map = new Map<TKey, Group<TKey, TValue>>();
array.forEach(t => {
const k = keyFn(t);
if (map.has(k)) {
map.get(k).values.push(t);
} else {
const g = {
key: k,
values: [t],
};
map.set(k, g);
result.push(g);
}
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment