Skip to content

Instantly share code, notes, and snippets.

@leoschur
Created December 20, 2021 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoschur/6ae5b99ef6fc89d674ae9918a291b10c to your computer and use it in GitHub Desktop.
Save leoschur/6ae5b99ef6fc89d674ae9918a291b10c to your computer and use it in GitHub Desktop.
groupBy function to group a given array by a given accessor and return the grouped values as a js Map
/**
* group an array by accessor
* @param arr array of elements
* @param accessor called on element, must return a value from the elements after which they are to be grouped
* @returns Map where keys are defined by accessor function and values are an array of elements
*/
const groupBy = (a, accessor) => {
if (!Array.isArray(a)) throw 'param a is not an array';
if (typeof(accessor) != 'function') throw 'param accessor is not a function';
return a.reduce(
(map, e) => map.set(accessor(e), [...map.get(accessor(e))||[], e]),
new Map()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment