22

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
   }
});
sadmicrowave
  • 39,964
  • 34
  • 108
  • 180

3 Answers3

40

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
   }
});
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • 2
    your code is wrong, `!($.inArray(iBarCode, myArray)` fails if the element is in position 0. you should use `!!~($.inArray(iBarCode, myArray)` instead. – Ravan Scafi Jun 30 '11 at 22:04
  • now my loop is not entering the if statement for any barcodes! the myArray is blank at the end – sadmicrowave Jun 30 '11 at 22:08
  • sadmicrowave, I wrote the if statement incorrectly, since inArray returns -1 if not found. I have updated the answer. – Gazler Jun 30 '11 at 22:10
  • 1
    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? – sadmicrowave Jun 30 '11 at 22:12
  • indexOf is not supported in IE. See this question. http://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-ie-browsers – Gazler Jun 30 '11 at 22:22
  • Also -1 isn't supposed in some browsers, this can be set as 'undefined'. – Oliver Tappin Aug 12 '12 at 00:22
9

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.

slaphappy
  • 6,894
  • 3
  • 34
  • 59
  • 5
    and if not using jquery, just use `if( myArray.indexOf(iBarCode) === -1 ){ // do something else }` – gcb Jan 11 '15 at 21:55
0

2021 Update

let myArray = [...new Set([...document.querySelectorAll('li.foo')].map(a => a.dataset.barcode))]

Working backwards: Create an array using the spread syntax from the matching elements, which Map only the data-barcode attribute. Use that to create a new Set, then create an array from that set

moose-o
  • 430
  • 3
  • 6