Skip to content

Instantly share code, notes, and snippets.

@miguel-leon
Last active June 19, 2017 00:35
Show Gist options
  • Save miguel-leon/9b0b0dbc408446c1f45f761d4b2206a4 to your computer and use it in GitHub Desktop.
Save miguel-leon/9b0b0dbc408446c1f45f761d4b2206a4 to your computer and use it in GitHub Desktop.
group by for arrays
/**
* @method Array.prototype.groupBy(group)
* Creates a dictionary grouping by an attribute or if `group` is a function, what it returns.
* @param {function|string} group - attribute name or function(item, index, array): string
* @returns {object.<array>}
*/
if (!Array.prototype.groupBy) {
Object.defineProperty(Array.prototype, 'groupBy', {
enumerable: false,
value: function groupBy(group) {
return this.reduce(function (hash, item, index, array) {
var key = typeof group === 'function' ? group(item, index, array) : String(item[group]);
if (!hash[key]) {
hash[key] = [];
}
hash[key].push(item);
return hash;
}, Object.create(null));
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment