Last active
May 25, 2018 07:03
-
-
Save joshuakemmerling/763bd4e5fc26bd803de8720707865c3a to your computer and use it in GitHub Desktop.
groupby function
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
/** | |
* 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