In the program, I fetch arrays of products from orders via API. The array contains a list with products that are duplicated. I need to remove the duplicate products in the array and sum their quantities.
This is what the array I get looks like:
const productsAll = [
{
name: 'Product 1',
ean: '1112223334445',
sku: '4445',
product_id: '70604566',
quantity: 1,
},
{
name: 'Product 1',
ean: '1112223334445',
sku: '4445',
product_id: '70604566',
quantity: 3,
},
{
name: 'Product 2',
ean: '1112223334446',
sku: '4446',
product_id: '60404533',
quantity: 2,
},
{
name: 'Product 3',
ean: '1112223334447',
sku: '4447',
product_id: '30504512',
quantity: 8,
},
];
I want to make it look like this after removing the duplicates and adding up the quantities:
Product 1 is reduced and the quantity is summed
[
{
name: 'Product 1',
ean: '1112223334445',
sku: '4445',
product_id: '70604566',
quantity: 4,
},
{
name: 'Product 2',
ean: '1112223334446',
sku: '4446',
product_id: '60404533',
quantity: 2,
},
{
name: 'Product 3',
ean: '1112223334447',
sku: '4447',
product_id: '30504512',
quantity: 8,
},
];
You can try the below approach to achieve this. Create an object (productsCheck
in my case) and loop through the productsAll
array. If the name already exists in the object then add the quantity, else simple add the product to your object ( i.e productsCheck
)
Working code:
const productsAll = [{
name: 'Product 1',
ean: '1112223334445',
sku: '4445',
product_id: '70604566',
quantity: 1,
},
{
name: 'Product 1',
ean: '1112223334445',
sku: '4445',
product_id: '70604566',
quantity: 3,
},
{
name: 'Product 2',
ean: '1112223334446',
sku: '4446',
product_id: '60404533',
quantity: 2,
},
{
name: 'Product 3',
ean: '1112223334447',
sku: '4447',
product_id: '30504512',
quantity: 8,
},
];
const productsCheck = {}
productsAll.forEach(product => {
if (product.name in productsCheck) {
productsCheck[product.name].quantity += product.quantity
} else {
productsCheck[product.name] = product
}
})
console.log(productsCheck)