-3

I am having an array of objects and want to remove duplicates

enter image description here

Like in the image i want to remove all duplicate values and get only single values and for the duplicates increase the quantity.

Rohan Fating
  • 2,135
  • 15
  • 24

2 Answers2

0

It seems like you are implementing how to add items in your cart. I assume you have a product class or similar name to create your objects.

export class Product {
  constructor(
    public name: string, public amount: number, quantity: number, productId: string){} 
}

I suggest you implement another class, say cart.

export class Cart {
    constructor(
        public product: Product, public quantity: number) {}
}

In your service.ts,

carts: Cart[];

addToCart(product: Product) {
    for (let i = 0; i < this.carts.length; i++) {
        if(this.carts[i].product.productId == product.productId) {
            this.carts[i].quantity = this.carts[i].quantity + 1;
            return;
        }// this code here to avoid duplicates and increase qty.
    }

    let cart = new Cart(product, 1);
    this.carts.push(cart);
}

You should have 3 different items in your cart, cs(3), dota(1), nfs(1). In my shopping cart, only 1 per item is added to cart, when you click on the product in my products component.

for(let i=0; i<products.length; i++){
  this.addToCart(products[i]);
}

This code works as show below

enter image description here

harold_mean2
  • 238
  • 1
  • 14
-1

Assuming arr is the array you want to remove duplicated from, here is a simple code to remove duplicated from it;

arr = Array.from(new Set(arr.map(x => {
  let obj;
  try {
    obj = JSON.stringify(x);
  } catch (e) {
    obj = x;
  }
  return obj;
}))).map(x => {
  let obj;
  try {
    obj = JSON.parse(x);
  } catch (e) {
    obj = x;
  }
  return obj;
});

Now, arr has no duplicates.

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
  • 1
    Using JSON.parse() and JSON.stringify() seems like a risky way to assume uniqueness. Example: `var foo = { a: 1, b: 2 }; var bar = { b: 2, a: 1 };`. – stealththeninja Sep 07 '17 at 04:35
  • Object property order is not guaranteed so yes, I'd say it matters. https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order A unique identifier in a hashtable is much more reliable, and happily it looks like the the OP has an id property to work with. – stealththeninja Sep 07 '17 at 04:41