Search code examples
javascriptjqueryarraysmatchshopping-cart

How to check if an item exist in a dynamic array?


I want to add Items to cartArray. If Array has already an item , I m going to write a function which prevents it adding it again by just increasing its quantity.. How can it be possible. Array Item has more than one element(e.g.id,price,quantity).

$(document).ready(function(){

    var cartArray = []; //array of cart Items data
    var total = 0;
    var shipping = 2;

    $(".addToCart").click(function(){

               var flag = 0;
        //Get all data of item to be added
            var id= $(this).data("id");
            var price= $(this).data("price");
            var image = $(this).data('image');
            var name = $(this).data("name");
            var quantity = $(this).data("quantity");
            var availability = $(this).data("availability");
            var weight = $(this).data("weight");


            //check if cart is empty to remove empty cart view
               if( (cartArray.length === 0) ) { 
                $("#empty-cart").css("display","none");}

        //Traverse the cart list to check if item already exists or not
             for(var i = 0; i < cartArray.length; ++i){
                 if (//what to do here to match id){
                 var increment= $( this ).find(".quantity").val();
                  increment++;
                  flag = 1;
                  $( this ).find(".quantity").val(increment);
                    return false;
                   }
                 }

          //Add new Item in cart
              if(flag == 0){
                  var cartItem =  "<li class='newItem'><p class='id'>"+id+"</p><div class='picture'><img src='"+image+"' ></div> <div class='details'><p class='name'>"+name+"</p><span class='weight'>"+weight+"</span><span> /</span> <span class='avail'>"+availability+"</span><p class='price'>"+price+"</p><a type='button' class='inc'>+</a><input type='text' class='quantity' value="+quantity+" ><a type='button' class='dec'>-</a></div> <a type='button' class='removeItem'><i class='fa fa-trash'></i></a></li>"
                     cartArray.push(cartItem);
                     localStorage.setItem('cartItem',JSON.stringify(cartArray)); 
                      var getItems = JSON.parse(localStorage.getItem('cartItem'));
                     // $("#cartList").prepend(cartItem);
                    $("#cartList li .id").css('display','none');
                      console.log("Item Added")
                   //increment in badge icon number when new item added in cart
                      var counterInc = parseInt($(".badge").html()) + 1;
                        $(".badge").html(counterInc);
                 }
})

Solution

  • EDIT

    after Alexander's comment you have to modify the solution

    function isInCart(id){
     var items = JSON.parse(localStorage.getItem('actualCart'));
     return !!items.filter(i=>i.id == id).length;
    }
    $(document).ready(function(){
        var actualCartArray = []; //array of cart Items data
        var cartArray = []; //array of cart Items html
        var total = 0;
        var shipping = 2;
    
        $(".addToCart").click(function(){
          if(isInCart($(this).data("id"))){
            return;
          }
                   var flag = 0;
            //Get all data of item to be added
                var id= $(this).data("id");
                var price= $(this).data("price");
                var image = $(this).data('image');
                var name = $(this).data("name");
                var quantity = $(this).data("quantity");
                var availability = $(this).data("availability");
                var weight = $(this).data("weight");
               actualCartArray.push({id,price,image,name,quantity,availability,weight});
    
                //check if cart is empty to remove empty cart view
                   if( (cartArray.length === 0) ) { 
                    $("#empty-cart").css("display","none");}
    
            //Traverse the cart list to check if item already exists or not
                 for(var i = 0; i < cartArray.length; ++i){
                     if (//what to do here to match id){
                     var increment= $( this ).find(".quantity").val();
                      increment++;
                      flag = 1;
                      $( this ).find(".quantity").val(increment);
                        return false;
                       }
                     }
    
              //Add new Item in cart
                  if(flag == 0){
                      var cartItem =  "<li class='newItem'><p class='id'>"+id+"</p><div class='picture'><img src='"+image+"' ></div> <div class='details'><p class='name'>"+name+"</p><span class='weight'>"+weight+"</span><span> /</span> <span class='avail'>"+availability+"</span><p class='price'>"+price+"</p><a type='button' class='inc'>+</a><input type='text' class='quantity' value="+quantity+" ><a type='button' class='dec'>-</a></div> <a type='button' class='removeItem'><i class='fa fa-trash'></i></a></li>"
                         cartArray.push(cartItem);
                         localStorage.setItem('cartItem',JSON.stringify(cartArray));
    localStorage.setItem('actualCart',JSON.stringify(actualCartArray));  
                          var getItems = JSON.parse(localStorage.getItem('cartItem'));
                         // $("#cartList").prepend(cartItem);
                        $("#cartList li .id").css('display','none');
                          console.log("Item Added")
                       //increment in badge icon number when new item added in cart
                          var counterInc = parseInt($(".badge").html()) + 1;
                            $(".badge").html(counterInc);
                     }
    })
    
    

    Create and use a function as the following. You pass an id and returns boolean if the item is in localStorage cart or not.

    function isInCart(id){
     var items = JSON.parse(localStorage.getItem('cartItem'));
     return !!items.filter(i=>i.id == id).length;
    }