Skip to content

Instantly share code, notes, and snippets.

@bamthomas
Created October 26, 2011 08:49
Show Gist options
  • Save bamthomas/1315814 to your computer and use it in GitHub Desktop.
Save bamthomas/1315814 to your computer and use it in GitHub Desktop.
groupBy javascript
function groupBy(jsonArray, fun) {
return jsonArray.reduce(function(accumulator, object) {
var value = fun(object);
if (Array.isArray(accumulator[value])) {
accumulator[value].push(object);
} else {
accumulator[value] = [object];
}
return accumulator;
}, {});
}
TestCase("Group by", {
"test group by": function () {
assertEquals({3: ["foo", "bar", "baz"]}, groupBy(["foo", "bar", "baz"], function(string) { return string.length;}));
assertEquals({"b": ["bar", "baz"], "f": ["foo"]}, groupBy(["foo", "bar", "baz"], function(string) { return string[0];}));
}
});
server: http://localhost:9876
load:
- groupBy.js
java -jar JsTestDriver-1.3.2.jar --port 9876 --tests all --config jsTestDriver.conf --browser /usr/bin/firefox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment