Last active
September 28, 2021 14:59
-
-
Save brunnerh/f45c3ef7aeb7185e603ac75cff53fdc9 to your computer and use it in GitHub Desktop.
Groups items in an array by a give selector.
This file contains 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
/** | |
* Groups items in a list by a give selector. | |
* @template T Type of the items. | |
* @template K Type of the grouping key. | |
* @param {Iterable<T>} list The items to group. | |
* @param {(item: T) => K} by Function for the selector by which to group. | |
*/ | |
function groupBy(list, by) | |
{ | |
/** @type {Map<K, T[]>} */ | |
const groups = new Map(); | |
for (const item of list) | |
{ | |
const key = by(item); | |
if (groups.has(key) == false) | |
groups.set(key, []); | |
const group = groups.get(key); | |
group.push(item); | |
}; | |
const groupList = []; | |
for (const [key, value] of groups) | |
groupList.push({ | |
key, | |
items: value, | |
}); | |
return groupList; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment