Created
December 20, 2021 17:03
-
-
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
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
/** | |
* 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