javascript find if value is NOT IN array

61,492

Solution 1

Jquery has an inArray() function.

var myArray = new Array();  var i = 0;
$("li.foo").each(function(){
   var iBarCode = $(this).attr('barcode');
   if( $.inArray(iBarCode, myArray) == -1 ){
      myArray[i++] = iBarCode;
      //do something else
   }
});

Solution 2

The in keyword search for properties, for instance when you want to know if an object has some method available. Since you are looking for values, it always returns false.

You should instead use an array search function as Gazler advises.

Share:
61,492

Related videos on Youtube

sadmicrowave
Author by

sadmicrowave

Updated on July 09, 2022

Comments

  • sadmicrowave
    sadmicrowave almost 2 years

    My problem with this is that the loop keeps going into the if statement even for duplicate barcodes. I'm trying to enter the if statement only for unique barcodes but at the end of the loop myArray has duplicates in it....why?

    var myArray = new Array();  var i = 0;
    $("li.foo").each(function(){
       var iBarCode = $(this).attr('barcode');
       if( !( iBarCode in myArray ) ){
          myArray[i++] = iBarCode;
          //do something else
       }
    });
    
  • Ravan Scafi
    Ravan Scafi almost 13 years
    your code is wrong, !($.inArray(iBarCode, myArray) fails if the element is in position 0. you should use !!~($.inArray(iBarCode, myArray) instead.
  • sadmicrowave
    sadmicrowave almost 13 years
    now my loop is not entering the if statement for any barcodes! the myArray is blank at the end
  • Gazler
    Gazler almost 13 years
    sadmicrowave, I wrote the if statement incorrectly, since inArray returns -1 if not found. I have updated the answer.
  • sadmicrowave
    sadmicrowave almost 13 years
    thank you that fixed it. just curious but is there a way to check if a value is in an array without jquery? like indexOf() or something?
  • Gazler
    Gazler almost 13 years
    indexOf is not supported in IE. See this question. stackoverflow.com/questions/1744310/…
  • Oliver Tappin
    Oliver Tappin almost 12 years
    Also -1 isn't supposed in some browsers, this can be set as 'undefined'.
  • gcb
    gcb over 9 years
    and if not using jquery, just use if( myArray.indexOf(iBarCode) === -1 ){ // do something else }