Angular 2 Remove Duplicate Values From An Array
I am having an array of objects and want to remove duplicates Like in the image i want to remove all duplicate values and get only single values and for the duplicates increase t
Solution 1:
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.
exportclassProduct {
constructor(public name: string, public amount: number, quantity: number, productId: string){}
}
I suggest you implement another class, say cart.
exportclassCart {
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
Solution 2:
Assuming arr
is the array you want to remove duplicated from, here is a simple code to remove duplicated from it;
arr = Array.from(newSet(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.
Post a Comment for "Angular 2 Remove Duplicate Values From An Array"