Skip to content

Instantly share code, notes, and snippets.

@vaderj
Last active June 12, 2018 15:12
Show Gist options
  • Save vaderj/a5f2f041acc868a3dca88c758d2204f2 to your computer and use it in GitHub Desktop.
Save vaderj/a5f2f041acc868a3dca88c758d2204f2 to your computer and use it in GitHub Desktop.
GroupBy property value within an array #Javascript
//src: https://www.consolelog.io/group-by-in-javascript
Array.prototype.groupBy = function(prop) {
return this.reduce(function(groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
/*
Usage:
var array = [{property: "value1", prop2 : "value2"},{property: "value1", prop2 : "value2"},{property: "value2", prop2 : "value1"},{property: "value2", prop2 : "value1"}]
array.groupBy("prop2")
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment