Skip to content

Instantly share code, notes, and snippets.

@awsp
Last active April 4, 2021 08:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save awsp/3f4b8d31acb6b55a7d95 to your computer and use it in GitHub Desktop.
Save awsp/3f4b8d31acb6b55a7d95 to your computer and use it in GitHub Desktop.
Javascript - multiple groupBy function
/**
* Javascript -
* Array multiple groupBy function
* Forked from http://codereview.stackexchange.com/questions/37028/grouping-elements-in-array-by-multiple-properties
*
* Usage:
* var list = [
* { foo: "bar", id: 1 },
* { foo: "barbar", id: 2 },
* { foo: "bar", id: 1 },
* { foo: "bar", id: 3 },
* { foo: "barbar", id: 2 },
* ];
*
* var newList = list.groupBy(function (item) {
* return [item.id];
* });
*/
if ( ! Array.prototype.groupBy) {
Array.prototype.groupBy = function (f)
{
var groups = {};
this.forEach(function(o) {
var group = JSON.stringify(f(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map(function (group) {
return groups[group];
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment