Skip to content

Instantly share code, notes, and snippets.

@fortwo
Last active November 26, 2020 21:10
Show Gist options
  • Save fortwo/395a3ffb2df4d0648ec7b0caf6cf5d37 to your computer and use it in GitHub Desktop.
Save fortwo/395a3ffb2df4d0648ec7b0caf6cf5d37 to your computer and use it in GitHub Desktop.
Based on the very well written https://gist.github.com/robmathers/1830ce09695f759bf2c4df15c29dd22d, this is a groupBy method that supports multiple keys.
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) => {
// returns an object containing keys and values of each 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