Skip to content

Instantly share code, notes, and snippets.

@Woodsphreaker
Created October 4, 2017 17:49
Show Gist options
  • Save Woodsphreaker/4bf3e307b61a1356a10c427a5088725c to your computer and use it in GitHub Desktop.
Save Woodsphreaker/4bf3e307b61a1356a10c427a5088725c to your computer and use it in GitHub Desktop.
grouping by column
const data = [
{
product_id: '2',
category_id: '13',
description: 'Anxious Armadillo',
price: '133',
quantity: '339',
},
{
product_id: '20',
category_id: '13',
description: 'Tender Tapir',
price: '22',
quantity: '490',
},
{
product_id: '25',
category_id: '20',
description: 'Uptight Unicorn',
price: '87',
quantity: '376',
},
{
product_id: '25',
category_id: '20',
description: 'Product 2',
price: '87',
quantity: '376',
},
{
product_id: '25',
category_id: '10',
description: 'Product 2',
price: '87',
quantity: '376',
},
{
product_id: '25',
category_id: '15',
description: 'Product 2',
price: '87',
quantity: '376',
},
];
const find = (acc, cur, el) => acc.find(obj => obj[el] == cur[el]);
const flatten = groupBy => (acc, cur) => {
const getNode = find(acc, cur, groupBy);
getNode
? getNode.products.push({
product_id: cur.product_id,
description: cur.description,
price: cur.price,
quantity: cur.quantity,
})
: acc.push({
[groupBy]: cur[groupBy],
products: [
{
product_id: cur.product_id,
description: cur.description,
price: cur.price,
quantity: cur.quantity,
},
],
});
return acc;
};
const group = (obj, groupBy = 'category_id') =>
obj.reduce(flatten(groupBy), []);
console.log(group(data, 'category_id'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment