Skip to content

Instantly share code, notes, and snippets.

@pmkhoa
Created May 9, 2017 22:51
Show Gist options
  • Save pmkhoa/986f1b218ab41f04eec87cb1753e5a49 to your computer and use it in GitHub Desktop.
Save pmkhoa/986f1b218ab41f04eec87cb1753e5a49 to your computer and use it in GitHub Desktop.
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
// Usage
// console.log(groupBy(['one', 'two', 'three'], 'length'));
/**
* 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];
});
};
}
/*
* Details: implementation for functional programming
* http://www.datchley.name/getting-functional-with-javascript-part-2/
* /
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment