Last active
March 2, 2024 14:28
-
-
Save Angelfire/b7d6c84d49a09e55378af3c01d969b89 to your computer and use it in GitHub Desktop.
Grouping With Reduce
This file contains hidden or 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
// Given an array of fruits in this format: | |
// [ | |
// { food: 'apple', type: 'fruit' }, | |
// { food: 'orange', type: 'fruit' }, | |
// { food: 'carrot', type: 'vegetable' } | |
// ] | |
// Let's turn it into an object with this format: | |
// { | |
// fruit: ['orange', 'apple'], | |
// vegetable: ['carrot'] | |
// } | |
// food is an array full of food objects | |
// let's group them by "type" and return them | |
function group(foods) { | |
return foods.reduce((acc, curr) => { | |
if (!acc[curr.type]) { | |
acc[curr.type] = []; | |
} | |
acc[curr.type].push(curr.food); | |
return acc; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment