So I have this kind of data (simplified version):
const itemList = [
{itemDetail: {date: '2020-12-30' , quantity: 5, productType: 'shirt' }},
{itemDetail: {date: '2021-01-05' , quantity: 4, productType: 'trouser' }},
{itemDetail: {date: '2020-12-30', quantity: 1, productType: 'shirt' }},
{itemDetail: {date: '2021-01-05', quantity: 2, productType: 'jacket'}}
]
The desired output:
const itemListFinalForm = [
{
date: '2020-12-30',
items: [{productType: 'shirt', quantity: 6}]
},
{
date: '2021-01-05',
items: [{productType: 'trouser', quantity: 4}, {productType: 'hat', quantity: 2}]
}
]
I’ve tried writing the pseudocode, but cant wrap my head around to actually implement it. Any kind of answer would be much appreciated. Thank you
Advertisement
Answer
Here i made a simple example below
const itemList = [{
itemDetail: {
date: '2020-12-30',
quantity: 5,
productType: 'shirt'
}
},
{
itemDetail: {
date: '2021-01-05',
quantity: 4,
productType: 'trouser'
}
},
{
itemDetail: {
date: '2020-12-30',
quantity: 1,
productType: 'shirt'
}
},
{
itemDetail: {
date: '2021-01-05',
quantity: 2,
productType: 'jacket'
}
}
]
var data = itemList.reduce((acc, item) => {
var d = acc.find(x => x.date == item.itemDetail.date);
if (!d) {
acc.push({
date: item.itemDetail.date,
items: [{
quantity: item.itemDetail.quantity,
productType: item.itemDetail.productType
}]
});
} else {
var type = d.items.find(x => x.productType == item.itemDetail.productType);
if (!type) {
d.items.push({
quantity: item.itemDetail.quantity,
productType: item.itemDetail.productType
})
} else type.quantity += item.itemDetail.quantity
}
return acc;
}, [])
console.log(data)