Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Created May 26, 2020 16:31
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 friendlyanon/9f396e735da4140327db6a909285cf8c to your computer and use it in GitHub Desktop.
Save friendlyanon/9f396e735da4140327db6a909285cf8c to your computer and use it in GitHub Desktop.
export const groupByUsing = (iterable, key, callback) => {
const mapper = typeof key !== "function" ? x => x[key] : key;
const map = new Map();
let i = -1;
for (const value of iterable) {
const mappedKey = mapper(value, ++i, key);
const mappedValue = callback(value, i, key);
const group = map.get(mappedKey);
if (group == null) {
map.set(mappedKey, [mappedValue]);
} else {
group.push(mappedValue);
}
}
return map;
};
export const groupBy = (iterable, key) => groupByUsing(iterable, key, x => x);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment