Skip to content

Instantly share code, notes, and snippets.

@brunnerh
Last active September 28, 2021 14:59
Show Gist options
  • Save brunnerh/f45c3ef7aeb7185e603ac75cff53fdc9 to your computer and use it in GitHub Desktop.
Save brunnerh/f45c3ef7aeb7185e603ac75cff53fdc9 to your computer and use it in GitHub Desktop.
Groups items in an array by a give selector.
/**
* 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