Suppose I have a array like this.
const info = [
{
productId: "1",
name: "This is product name 1",
sellerId: "12",
price: 30,
},
{
productId: "2",
name: "This is product name 2",
sellerId: "12",
price: 50
},
{
productId: "3",
name: "This is product name 3",
sellerId: "13",
price: 50
}
]
**This is dynamic array. Array value can be changed.
Now I have to combine this array or filter this array. I have not any idea about how can I write function. But my result will be like this-
const result = [
{
sellerId: "12",
productIds: [ //Combine products by similar sellerId
{
name: "This is product name 1",
productId: "1"
},
{
name: "This is product name 2",
productId: "2"
}
],
total: 80 //Total price of this two product
},
{
sellerId: "13",
productIds: [
{
name: "This is product name 3",
productId: "3"
}
],
total: 50
}
]
Please do not close my question. I almost check all similar questions. But I have a different issue here. Just please help me.
CodePudding user response:
You could use .reduce
and check if you already have that sellerId, if so, push the item and update total, else create the item:
const info = [
{
productId: "1",
name: "This is product name 1",
sellerId: "12",
price: 30,
},
{
productId: "2",
name: "This is product name 2",
sellerId: "12",
price: 50
},
{
productId: "3",
name: "This is product name 3",
sellerId: "13",
price: 50
}
]
const result = info.reduce((carry, el) => {
const { sellerId, price, ...rest } = el;
const i = carry.find((c) => c.sellerId === sellerId);
if (!i) {
carry.push({ sellerId, productIds: [rest], total: price })
} else {
i.productIds.push(rest);
i.total = price;
}
return carry;
}, []);
console.log(result);
CodePudding user response:
You can use Object.values()
and Array#reduce()
methods as follows:
const
input = [ { productId: "1", name: "This is product name 1", sellerId: "12", price: 30, }, { productId: "2", name: "This is product name 2", sellerId: "12", price: 50 }, { productId: "3", name: "This is product name 3", sellerId: "13", price: 50 } ],
output = Object.values(
input.reduce(
(acc,{productId,name,sellerId,price}) =>
({
...acc,
[sellerId]:{...(acc[sellerId] || {}),
sellerId,
productIds: [...(acc[sellerId] && acc[sellerId]['productIds'] || []),
{name,productId}]
}
}),
{})
);
console.log( output );