Skip to content

Instantly share code, notes, and snippets.

@joshuakemmerling
Last active May 25, 2018 07:03
Show Gist options
  • Save joshuakemmerling/763bd4e5fc26bd803de8720707865c3a to your computer and use it in GitHub Desktop.
Save joshuakemmerling/763bd4e5fc26bd803de8720707865c3a to your computer and use it in GitHub Desktop.
groupby function
/**
* Creates an object of groupings.
*
* @param {Function|String} f - The function that returns value to group by or object key.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* array.groupBy('city');
* array.groupBy(function (obj) { return obj.city; });
* array.groupBy((obj) => { return obj.city; });
* array.groupBy(({ city }) => city);
*/
Array.prototype.groupBy = function (f) {
return this.reduce((o, v) => {
const key = typeof f === 'string' ? v[f] : f(v)
o[key] || (o[key] = [])
o[key].push(v)
return o
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment