Array.groupBy, groupByToMap
Minimal reverse-engineered implementations of the recently proposed Array.groupBy and Array.groupByToMap (ES)
by Nicholas Berlette
JavaScript
Object.defineProperties(Array.prototype, {
groupBy: {
/**
* Array.prototype.groupBy
* @param {string | number} field - the common field to group items by
* @param {*} [thisArg] - the value to pass to the function as "this"
* @returns {Record<string | number, any>}
*/
value: function (field, thisArg = this) {
return (thisArg || this).reduce((grouped, entry) => {
grouped[entry[field]] = [...(grouped[entry[field]] || []), entry];
return grouped;
}, {})
}
},
/**
* Array.prototype.groupByToMap
* @param {string | number} field - the common field to group items by
* @param {*} [thisArg] - the value to pass to the function as "this"
* @returns {Map<string | number, any>}
*/
groupByToMap: {
value: function (field, thisArg = this) {
return new Map(Object.entries(Array.prototype.groupBy.call(thisArg, field)));
}
}
});
var movies = [
{
"Title": "Inception",
"Year": "2010",
"Director": "Christopher Nolan"
},
{
"Title": "Interstellar",
"Year": "2009",
"Director": "Christopher Nolan"
},
{
"Title": "Avatar",
"Year": "2009",
"Director": "James Cameron"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Director": "Christopher Nolan"
},
{
"Title": "Batman Begins",
"Year": "2008",
"Director": "Christopher Nolan"
},
{
"Title": "Batman Ends",
"Year": "2010",
"Director": "Christopher Nolan"
},
{
"Title": "Batman Fails",
"Year": "2001",
"Director": "Christopher Nolan"
}
];
console.log(movies.groupBy('Year'));
console.log([...movies.groupByToMap('Year')])