Skip to content

Instantly share code, notes, and snippets.

@fortwo
Created June 22, 2020 12:45
Show Gist options
  • Save fortwo/33506dd4c86c6819d7a3963e09a8764e to your computer and use it in GitHub Desktop.
Save fortwo/33506dd4c86c6819d7a3963e09a8764e to your computer and use it in GitHub Desktop.
A more readable and annotated version of the Javascript groupBy from Ceasar Bautista (https://stackoverflow.com/a/34890276/1376063)
const groupBy = (data, keys) => { // `data` is an array of objects, `keys` is the array of keys (or property accessor) to group by
// reduce runs this anonymous function on each element of `data` (the `item` parameter,
// returning the `storage` parameter at the end
return data.reduce((storage, item) => {
//
const groupValues = keys.reduce((values, key) => {
values[key] = item[key];
return values;
}, {});
// get the first instance of the key by which we're grouping
const group = Object.values(groupValues).join(' ');
// set `storage` for this instance of group to the outer scope (if not empty) or initialize it
storage[group] = storage[group] || [];
// add this item to its group within `storage`
if (keys.every((key) => item[key] === groupValues[key])) {
storage[group].push(item);
}
// return the updated storage to the reduce function, which will then loop through the next
return storage;
}, {}); // {} is the initial value of the storage
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment