Skip to content

Instantly share code, notes, and snippets.

@killa-kyle
Created December 28, 2021 18:14
Show Gist options
  • Save killa-kyle/8c029e8fc37307650ef3860213e7ce7d to your computer and use it in GitHub Desktop.
Save killa-kyle/8c029e8fc37307650ef3860213e7ce7d to your computer and use it in GitHub Desktop.
const products = [
{ name: 'apples', category: 'fruits', count: 1 },
{ name: 'oranges', category: 'fruits', count: 2 },
{ name: 'potatoes', category: 'vegetables', count: 1 },
{ name: 'kettle chips', category: 'snacks', count: 3 },
];
const groupByCategory = products.reduce((group, product) => {
const { category } = product;
group[category] = group[category] ?? [];
group[category].push(product);
return group;
}, {});
const groupBy = (arr, key) => arr.reduce((group, item) => {
group[item[key]] = group[item[key]] ?? [];
group[item[key]].push(item)
return group
}, {})
console.log(groupByCategory);
console.log(groupBy(products, 'count'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment