Skip to content

Instantly share code, notes, and snippets.

@davidchambers
Created June 27, 2020 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidchambers/f4b58645b752df0295dc461513c1824b to your computer and use it in GitHub Desktop.
Save davidchambers/f4b58645b752df0295dc461513c1824b to your computer and use it in GitHub Desktop.
//# groupBy :: (a -> b) -> Array a -> Array (Array a)
//.
//. Group the given elements in accordance with the given comparator.
//.
//. > groupBy (x => x % 3) ([1, 2, 3, 4, 5, 6, 7, 8, 9])
//. [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
const groupBy = f => xs => {
const groups = [];
const ys = [];
xs.forEach (x => {
const y = f (x);
const idx = ys.indexOf (y);
if (idx < 0) {
ys.push (y);
groups.push ([x]);
} else {
groups[idx].push (x);
}
});
return groups;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment