Skip to content

Instantly share code, notes, and snippets.

@nblackburn
Last active December 7, 2024 21:08
Show Gist options
  • Save nblackburn/138fc48908c20fef64b436b4c04d5c1d to your computer and use it in GitHub Desktop.
Save nblackburn/138fc48908c20fef64b436b4c04d5c1d to your computer and use it in GitHub Desktop.
Group By

Group By

Group items by the key returned in the callback.

const data = [
    { id: 'a' },
    { id: 'b' },
    { id: 'a' }
];

groupBy(data, (d) => d.id); // { a: [ { id: 'a' }, { id: 'a' } ], b: [ { id: 'b' } ] }
groupByArray(data, (d) => d.id); // [ { key: 'a', items: [{ id: 'a' }, { id: 'a' }] }, { key: 'b', items: [{ id: 'b' }] } ]
const groupBy = (items, callback) => {
const groups = {};
items.forEach((item) => {
const key = callback(item) ?? 'ungrouped';
const keys = Array.isArray(key) ? key : [key];
// Create the group if it doesn't exist.
keys.forEach((key) => {
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
});
});
return groups;
};
const groupByArray = (items, callback) => {
const groups = groupBy(items, callback);
return Object.keys(groups).map((group) => {
return {
key: group,
items: groups[group]
};
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment