There is an array of objects. I need to group it by one of the object keys.
const foods = [
{id: 1, title: 'apple', type: 'fruit'},
{id: 2, title: 'banana', type: 'fruit'},
{id: 3, title: 'bird', type: 'meat'},
{id: 4, title: 'beer', type: 'drinks'},
{id: 5, title: 'cow', type: 'meat'},
]
should get the following result:
const foodTypes = [
{
type: 'fruit',
foods: [
{id: 1, title: 'apple', type: 'fruit'},
{id: 2, title: 'banana', type: 'fruit'},
]
},
{
type: 'meat',
foods: [
{id: 3, title: 'cow', type: 'meat'},
{id: 4, title: 'bird', type: 'meat'},
]
},
{
type: 'drinks',
foods: [
{id: 5, title: 'beer', type: 'drinks'},
]
},
]
I tried to solve through the reduce method, but something went wrong. Without using libraries.
const grouper = key => array =>
array.reduce((acc, val) => {
const property = val[key];
acc[property] = acc[property] || [];
acc[property].push(val);
return acc;
}, {})