javascript find if value is NOT IN array

Viewed 61771

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

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

Related