Last active
April 4, 2021 08:45
-
-
Save awsp/3f4b8d31acb6b55a7d95 to your computer and use it in GitHub Desktop.
Javascript - multiple groupBy function
This file contains 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
/** | |
* 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