Created
June 12, 2014 23:52
-
-
Save joshcarr/5e3bce5e75dc68accec0 to your computer and use it in GitHub Desktop.
Javascript 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
function groupBy( array , f ) { | |
var groups = {}; | |
array.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]; | |
}); | |
} | |
var list = [ | |
{"name": "John","Average":15,"High":10,"DtmStamp":1358226000000}, | |
{"name": "Jane","Average":16,"High":92,"DtmStamp":1358226000000}, | |
{"name": "Jane","Average":17,"High":45,"DtmStamp":1358226000000}, | |
{"name": "John","Average":18,"High":87,"DtmStamp":1358226000000}, | |
{"name": "Jane","Average":15,"High":10,"DtmStamp":1358226060000}, | |
{"name": "John","Average":16,"High":87,"DtmStamp":1358226060000}, | |
{"name": "John","Average":17,"High":45,"DtmStamp":1358226060000}, | |
{"name": "Jane","Average":18,"High":92,"DtmStamp":1358226060000} | |
] | |
// USING IT | |
var sorted = groupBy(list, function(item){ | |
return [item.name]; | |
}); | |
var sorted2 = groupBy(list, function(item){ | |
return [item.name, item.DtmStamp]; | |
}); | |
console.log(sorted, sorted2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment