Skip to content

Instantly share code, notes, and snippets.

@Juandresyn
Last active July 9, 2019 21:48
Show Gist options
  • Save Juandresyn/84079e1506eab6d5eafc2fb18ede47cc to your computer and use it in GitHub Desktop.
Save Juandresyn/84079e1506eab6d5eafc2fb18ede47cc to your computer and use it in GitHub Desktop.
// As a prototype
/*
* @param property string - The object propperty to group by.
*/
Array.prototype.groupBy = function (property) {
const filtered = this.reduce(function(item, x) {
if (!item[x[property]]) { item[x[property]] = []; }
item[x[property]].push(x);
return item;
}, []);
const temp = {};
Object.keys(filtered).forEach(i => temp[i] = filtered[i]);
return temp;
}
// As a function
/*
* @param arr array - The array to group.
* @param property string - The object propperty to group by.
*/
export const groupBy = function (arr, property) {
const filtered = arr.reduce(function(item, x) {
if (!item[x[property]]) { item[x[property]] = []; }
item[x[property]].push(x);
return item;
}, []);
const temp = {};
Object.keys(filtered).forEach(i => temp[i] = filtered[i]);
return temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment