Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created October 26, 2022 03:03
Show Gist options
  • Save yano3nora/ef21e8b4b16406c33ac8879700bdd542 to your computer and use it in GitHub Desktop.
Save yano3nora/ef21e8b4b16406c33ac8879700bdd542 to your computer and use it in GitHub Desktop.
[js: group-by] #js
/**
* @link https://qiita.com/nagtkk/items/e1cc3f929b61b1882bd1
* @example
* const result = groupBy(users, user => user.role)
* .filter(([role, _users]) => role === 'admin')
*/
export const groupBy = <K, V>(
array: readonly V[],
getKey: (cur: V, idx: number, src: readonly V[]) => K
): [K, V[]][] =>
Array.from(
array.reduce((map, cur, idx, src) => {
const key = getKey(cur, idx, src)
const list = map.get(key)
if (list) {
list.push(cur)
} else {
map.set(key, [cur])
}
return map
}, new Map<K, V[]>())
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment