Skip to content

Instantly share code, notes, and snippets.

@Angelfire
Last active March 2, 2024 14:28
Show Gist options
  • Save Angelfire/b7d6c84d49a09e55378af3c01d969b89 to your computer and use it in GitHub Desktop.
Save Angelfire/b7d6c84d49a09e55378af3c01d969b89 to your computer and use it in GitHub Desktop.
Grouping With Reduce
// 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