1

I am using Angular as my framework. I have a function that is called whenever the array has been mutated. I need to check the array every time this function is called to see if it has duplicate items and if it does I need to edit the original item and remove the last item from the array.

I am building a shopping cart. so when a duplicate item is added to the array I need to change the quantity value in the original item and remove the last pushed item.

component function:

ngDoCheck() {
    var changes = this.differ.diff(this.shoppingCart); // check for changes
    if (changes) {
      clearTimeout(this.timer);
      this.cartOpen = true;
      this.itemsInCart = this.numberOfItemsinCart(this.shoppingCart);
      this.cartTotal = this.totalCartAmount(this.shoppingCart);

     //check if this.shoppingCart has a duplicate item
     //if array does have a duplicate 
     //change qty value in original item and
     //remove the last item added

   }
 }

My array of objects example:

{
    "id": 6,
    "product_name": "name of product",
    "sku": "26-008b",
    "description": "description of product",
    "product_link": "link",
    "cat_id": "categoryId",
    "cat_name": "Category name",
    "related_products": [],
    "sub_cat_name": "sub category name",
    "price": price,
    "qty": 1
}

ANy help would be greatly appreciated as I am out of ideas or have been staring at this code for too long.

Travis Michael Heller
  • 1,210
  • 3
  • 16
  • 34
  • Controlling duplication before and accordingly inserting new record to array or updating existing record is reasonable. – yılmaz Oct 07 '17 at 19:59
  • 1
    See my answer here. If it helps, please check my answer: https://stackoverflow.com/questions/46087273/angular-2-remove-duplicate-values-from-an-array – harold_mean2 Oct 07 '17 at 20:01

2 Answers2

1

You can use javascript buildin function about array Array.indexOf(item) and Array.prototype.lastIndexOf(item)

if(Array.indexOf(item) == Array.prototype.lastIndexOf(item)) {
    // change value in position given by indexOf
    // delete last index
}
1

Instead of removing item after adding, you need to check for duplicate item before adding it,

You could check for duplicate items using .filter

var duplicates = this.shoppingCart.filter(this.product_name ==='yourSampleName');
if(duplicates && duplicates.length > 0){
//add items here 
 this.shoppingCart.push(whatever);
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396