Created
October 26, 2022 03:03
-
-
Save yano3nora/ef21e8b4b16406c33ac8879700bdd542 to your computer and use it in GitHub Desktop.
[js: group-by] #js
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
/** | |
* @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