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 3
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
}
});
6 Comments
!($.inArray(iBarCode, myArray)
fails if the element is in position 0. you should use !!~($.inArray(iBarCode, myArray)
instead.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.
1 Comment
if( myArray.indexOf(iBarCode) === -1 ){ // do something else }
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