Skip to content

Instantly share code, notes, and snippets.

@flavioribeirojr
Created March 22, 2020 13:21
Show Gist options
  • Save flavioribeirojr/3f9f2b2cea2a783928b2646554e39b50 to your computer and use it in GitHub Desktop.
Save flavioribeirojr/3f9f2b2cea2a783928b2646554e39b50 to your computer and use it in GitHub Desktop.
Using reduce to group an array of products by category
const products = [
{
name: 'Disposable Mask',
price: 8.75,
category: 'Health'
},
{
name: 'Painkiller',
price: 2.35,
category: 'Health'
},
{
name: 'White Chair',
price: 24.50,
category: 'Furniture'
}
];
const productCategoryGrouper = ( productsByCategory, product ) => ({
...productsByCategory,
[product.category]: [
...(productsByCategory[product.category] || []),
product
]
});
const productsByCategory = products.reduce(productCategoryGrouper, {});
/**
productsByCategory:
{
Health: [
{
name: 'Disposable Mask',
price: 8.75,
category: 'Health'
},
{
name: 'Painkiller',
price: 2.35,
category: 'Health'
}
],
Furniture: [
{
name: 'White Chair',
price: 24.50,
category: 'Furniture'
}
]
}
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment