Skip to content

Instantly share code, notes, and snippets.

@codeallday31
Created July 17, 2023 08:43
Show Gist options
  • Save codeallday31/dd63a96581d0ae3a20ead2608448dd09 to your computer and use it in GitHub Desktop.
Save codeallday31/dd63a96581d0ae3a20ead2608448dd09 to your computer and use it in GitHub Desktop.
groupby
function _group_by(list, key) {
const groupBy = (array, key) => {
// Return the end result
return array.reduce((result, currentValue) => {
// If an array already present for key, push it to the array. Else create an array and push the object
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
return result;
}, []); // empty object is the initial value for result object
};
// Group by key as key to the list array
return groupBy(list, key).filter(item => item);
},
function groupBy(data, key) {
return data.reduce(function(storage, item) {
const group = item[key];
storage[group] = storage[group] || [];
storage[group].push(item);
return storage;
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment