I’m trying to arrange this array of products by categories. For now, I get the count of each category but I can’t figure out how to make this two dimension array output.
let products = [ {name: 'Tequila', category: 'drink'}, {name: 'Beer', category: 'drink'}, {name: 'Burger', category: 'food'}, {name: 'Shawarma', category: 'food'}, {name: 'Wine', category: 'drink'}, {name: 'Gelatto', category: 'dessert'} ]; /*expected ouput let arranged = [[ {name: 'Tequila', category: 'drink'}, {name: 'Beer', category: 'drink'}, {name: 'Wine', category: 'drink'} ], [ {name: 'Burger', category: 'food'}, {name: 'Shawarma', category: 'food'} ], [ {name: 'Gelatto', category: 'dessert'} ]]; */
This is my code for now:
let products = [ {name: 'Tequila', category: 'drink'}, {name: 'Beer', category: 'drink'}, {name: 'Burger', category: 'food'}, {name: 'Shawarma', category: 'food'}, {name: 'Wine', category: 'drink'}, {name: 'Gelatto', category: 'dessert'} ]; let arranged = {}; products.map(x => arranged[x.category] = 1 + (arranged[x.category] || 0)); console.log(arranged);
Advertisement
Answer
You can group elements by reducing over the array using an object to store elements belonging to each category. To get the grouped categories, we can use Object.values
.
let products = [{name: 'Tequila', category: 'drink'}, {name: 'Beer', category: 'drink'}, {name: 'Burger', category: 'food'}, {name: 'Shawarma', category: 'food'}, {name: 'Wine', category: 'drink'}, {name: 'Gelatto', category: 'dessert'}]; const res = Object.values( products.reduce((acc,curr)=>( (acc[curr.category] = acc[curr.category] || []).push(curr), acc ), {}) ); console.log(res);