Skip to content

Instantly share code, notes, and snippets.

@minitech
Created June 28, 2012 16:30
Show Gist options
  • Save minitech/3012322 to your computer and use it in GitHub Desktop.
Save minitech/3012322 to your computer and use it in GitHub Desktop.
Grouping in JavaScript
// A grouping function for JavaScript.
// Created by Ryan O'Hara.
// Usage:
// group([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(x) { return x % 2; });
// group({a: 20, b: 30, c: 40, d: 50}, function(x) { return x % 20; });
// Result:
// [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
// [{a: 20, c: 40}, {b: 30, d: 50}]
function group(obj, func, thisArg) {
var resultKeys = [];
var resultValues = [];
var i, j, k, l;
if(Object.prototype.toString.call(obj) === '[object Array]') {
for(i = 0, l = obj.length; i < l; i++) {
k = func.call(thisArg, obj[i], i, obj);
j = resultKeys.indexOf(k);
if(~j) {
resultValues[j].push(obj[i]);
} else {
resultKeys.push(k);
resultValues.push([obj[i]]);
}
}
return resultValues;
}
for(i in obj) {
if(obj.hasOwnProperty(i)) {
k = func.call(thisArg, obj[i], i, obj);
j = resultKeys.indexOf(k);
if(~j) {
resultValues[j][i] = obj[i];
} else {
resultKeys.push(k);
resultValues.push({});
resultValues[resultValues.length - 1][i] = obj[i];
}
}
}
return resultValues;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment