0

const all_products = [
  { fruits: 'apples', category: 'fruits' },
  { fruits: 'oranges', category: 'fruits' },
  { fruits: 'potatoes', category: 'vegetables' }
];


this is the array of object

=>i want this output

const groupByCategory = {
'fruits': [
{ fruits: 'apples', category: 'fruits' },
{ fruits: 'oranges', category: 'fruits' },
],
'vegetables': [
{ fruits: 'potatoes', category: 'vegetables' }
]
};

=>i solved it by reduce method

const groupByCategory = products.reduce((group, product) => {
const { category } = product;
group[category] = group[category] ?? [];
group[category].push(product);
return group;
}, {});

console.log(groupByCategory);

=>and get answer successfully, =>is there any other easier way to did it without any 3rd party package?

0 Answers0