0

This is the structure of my Array:

[{"stockCode":"PALLET CARDS","quantity":"2"},
 {"stockCode":"PALLET CARDS","quantity":"3"},
 {"stockCode":"CBL202659/A","quantity":"1"},
 {"stockCode":"CBL201764","quantity":"3"}] 

When the order button is clicked I would like to check if a stockCode exists in this array. However each time I do this I get -1 returned.

This is the code where I check for the stockCode:

$(".orderBtn").click(function(event){
        //Check to ensure quantity > 0
        if(quantity == 0){
            console.log("Quantity must be greater than 0")
        }else{//It is so continue
            //Show the order Box
            $(".order-alert").show();
            event.preventDefault();

            //Get reference to the product clicked
            var stockCode = $(this).closest('li').find('.stock_code').html();
            //Get reference to the quantity selected
            var quantity = $(this).closest('li').find('.order_amount').val();

            //Order Item (contains stockCode and Quantity) - Can add whatever data I like here
            var orderItem = {
            'stockCode' : stockCode,
            'quantity'  : quantity
            };

            //Check if cookie exists 
            if($.cookie('order_cookie') === undefined){

            console.log("Creating new cookie");
            //Add object to the Array
            productArray.push(orderItem);

            }else{//Already exists

            console.log("Updating the cookie")
            productArray = JSON.parse($.cookie('order_cookie'));

            //Check if the item already exists in the Cookie and update qty
            if(productArray.indexOf(stockCode)!= -1){

                //Get the original item and update
                console.log("UPDATING EXISTING ENTRY " + productArray.indexOf("PALLET CARDS"));
            }
            else{
                console.log("ADDING NEW ENTRY ");
                //Insert the item into the Array
                //productArray.push(orderItem);
            }
            }
        }

        //Update the Cookie
        $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });

        //Testing output of Cookie
        console.log($.cookie('order_cookie'));
    });

I get a reference to the stockCode when the user clicks on the order button:

        var stockCode = $(this).closest('li').find('.stock_code').html();

I would like to check if this stockCode is already in the array and if it is then I will not be adding a new entry, but rather, updating an existing one.

2
  • duplicate this has been asked before... You can't do a straight indexOf on an object array. You have to compare each element in the array. Commented Jun 10, 2014 at 10:20
  • question still unanswered? Commented Aug 24, 2015 at 15:54

3 Answers 3

3

i hope I'm getting you right:

   function findByStockCode(code, stockCodeArr){
           return stockCodeArr.filter(function(elem){
              return elem.stockCode == code;
           });
   }

this ofcourse would give you an array back. If the length is greater than zero an element with the given code is in the array already. I think the filter-function has been added at ECMA5 so probably IE8 won't support it.
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter][1] mentions a fallback for the case that filter is not implemented in the current browser.
Anyway there's a similiar jQuery-function that in which 'this' refers to the actual element:

function jQueryFindByStockCode(code, stockCodeArr){
               return $(stockCodeArr).filter(function(){
                  return this.stockCode == code;
               });
       }

Edit:
As DhruvPathak mentioned $.grep might be a more appropriate solution than jQuery's filter. (Grep vs Filter in jQuery?)

I looked up again for a solution with a better performance (seems) you have it to write on your own (it's pretty simple anyway):

//for defined, non-null values
function findFirstByProperty(arr, prop, value){
    for(var i = 0 ; i < arr.length; i++){
         if(arr[i]!=null && "undefined" !== typeof arr[i] && arr[i][prop] == value) 
             return arr[i];
    }
    return null;
}

This should have a better performance (especially for big arrays). In average (assuming there's such an element in array) it should in average be twice as fast as filter and grep (since it stops at first match).

Sign up to request clarification or add additional context in comments.

3 Comments

You should actually use jQuery's $.grep method (as mentioned by @DhruvPathak) for this instead of $().filter, as the second is for DOM collections.
I had a mistaken memory of grep. I thought it would stop at first found element. So both solutions seem to have a non-perfect performance for this issue. Maybe a own function should be written here for performance-hunters.
That would be find() in Harmony.
0

use jquery grep , to match elements of your array which have "stockcode" key equal to your stockCode

http://api.jquery.com/jquery.grep/

Comments

-2

I think you need to use like this :

$.inArray( stockCode, productArray)

More information here.

2 Comments

before downvoting can someone dare to put comment
then what is the issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.