Skip to content

Instantly share code, notes, and snippets.

@sifu
Created October 15, 2012 09:19
Show Gist options
  • Save sifu/3891620 to your computer and use it in GitHub Desktop.
Save sifu/3891620 to your computer and use it in GitHub Desktop.
a group-by implementation
function groupBy( array, key ) {
var result = {};
var by, property;
var item, i=0;
var isAlreadyFunction = typeof( key ) === 'function';
if( isAlreadyFunction ) {
by = key;
} else {
by = function( item ) {
return item[ key ];
};
}
while( item = array[ i ] ) {
property = by( item );
( result[ property ] || ( result[ property ] = [] ) ).push( item );
i++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment