Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created November 15, 2019 12:30
Show Gist options
  • Select an option

  • Save gkucmierz/9525f8c173f621aa21596fd0029c5956 to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/9525f8c173f621aa21596fd0029c5956 to your computer and use it in GitHub Desktop.
groupBy
function groupBy(arr, fn) {
fn = fn || ((o) => o);
let g = [];
let v = [];
for (let i = 0; i < arr.length; ++i) {
let val = fn(arr[i]);
let idx = g.indexOf(val);
if (idx === -1) {
g.push(val);
v.push([arr[i]]);
} else {
v[idx].push(arr[i]);
}
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment