javascript find if value is NOT IN array

sadmicrowave picture sadmicrowave · Jun 30, 2011 · Viewed 58.8k times · Source

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
   }
});

Answer

Gazler picture Gazler · Jun 30, 2011

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
   }
});