Skip to content

Instantly share code, notes, and snippets.

@parkerproject
Forked from robmathers/groupBy.js
Created August 10, 2022 01:32
Show Gist options
  • Save parkerproject/2a913612b25c980f63c066176746bcf4 to your computer and use it in GitHub Desktop.
Save parkerproject/2a913612b25c980f63c066176746bcf4 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)
var groupBy = function(data, key) { // `data` is an array of objects, `key` is the key (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(function(storage, item) {
// get the first instance of the key by which we're grouping
var group = item[key];
// 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`
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