Last active
June 12, 2018 15:12
-
-
Save vaderj/a5f2f041acc868a3dca88c758d2204f2 to your computer and use it in GitHub Desktop.
GroupBy property value within an array #Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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