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.
Related videos on Youtube
Author by
sadmicrowave
Updated on July 09, 2022Comments
-
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 almost 13 yearsyour code is wrong,
!($.inArray(iBarCode, myArray)
fails if the element is in position 0. you should use!!~($.inArray(iBarCode, myArray)
instead. -
sadmicrowave almost 13 yearsnow my loop is not entering the if statement for any barcodes! the myArray is blank at the end
-
Gazler almost 13 yearssadmicrowave, I wrote the if statement incorrectly, since inArray returns -1 if not found. I have updated the answer.
-
sadmicrowave almost 13 yearsthank 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 almost 13 yearsindexOf is not supported in IE. See this question. stackoverflow.com/questions/1744310/…
-
Oliver Tappin almost 12 yearsAlso -1 isn't supposed in some browsers, this can be set as 'undefined'.
-
gcb over 9 yearsand if not using jquery, just use
if( myArray.indexOf(iBarCode) === -1 ){ // do something else }