Last active
June 19, 2017 00:35
-
-
Save miguel-leon/9b0b0dbc408446c1f45f761d4b2206a4 to your computer and use it in GitHub Desktop.
group by for arrays
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
/** | |
* @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