Last active
July 14, 2016 07:02
-
-
Save sergeyt/18ce409a63a44cb4c4923d04d8571f56 to your computer and use it in GitHub Desktop.
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
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