Created
December 28, 2021 18:14
-
-
Save killa-kyle/8c029e8fc37307650ef3860213e7ce7d to your computer and use it in GitHub Desktop.
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: '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