How to detect if selected product code exist in MY CART, if the product code exist, do not insert it into MY CART array, instead add the quantity of the selected product into the existing product in MY CART.
The code I wrote get to add in all the product selected into MY CART, which is not quite efficient to see all the same product get piled up. It will be better to have this feature to sum the quantity if the product exist.
var cartlist= new Array();
$(".addtocart").on('click', function() {
var prdcode = $("#prod_code");
var description = $("#prod_desc");
var qty= $("#prod_qty");
var itemlist = new Array();
itemlist.push(prdcode );
itemlist.push(description );
itemlist.push(qty);
cartlist.push(itemlist);
for (var i = 0; i < cartlist.length-1; i++) {
if(cartlist[i+1] === cartlist[i]){
continue;
//action to sum qty if code exist in cart
}
}
});
MY CART
0: Array(3){
0: "ABC123"
1: "DESCRIPTION FOR ABC123"
2: "1"
}
1: Array(3){
0: "DEF456"
1: "DESCRIPTION FOR DEF456"
2: "2"
}
TO BE ADDED IN CART
0: Array(3){
0: "ABC123"
1: "DESCRIPTION FOR ABC123"
2: "1"
}
1: Array(3){
0: "GHI789"
1: "DESCRIPTION FOR GHI789"
2: "1"
}
EXPECTED OUTCOME (AFTER ADDED IN CART)
0: Array(3){
0: "ABC123"
1: "DESCRIPTION FOR ABC123"
2: "2"
}
1: Array(3){
0: "DEF456"
1: "DESCRIPTION FOR DEF456"
2: "2"
}
2: Array(3){
0: "GHI789"
1: "DESCRIPTION FOR GHI789"
2: "1"
}