Created
March 22, 2020 13:21
-
-
Save flavioribeirojr/3f9f2b2cea2a783928b2646554e39b50 to your computer and use it in GitHub Desktop.
Using reduce to group an array of products by category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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