Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript find if value is NOT IN array

Tags:

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    } }); 
like image 477
sadmicrowave Avatar asked Jun 30 '11 21:06

sadmicrowave


People also ask

How do you check if a value is in an array?

isArray(variableName) method to check if a variable is an array. The Array. isArray(variableName) returns true if the variableName is an array. Otherwise, it returns false .

How do you check if a value already exists in an array JavaScript?

The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.

How do you check if a value is not present in an array TypeScript?

Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise.


1 Answers

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    } }); 
like image 193
Gazler Avatar answered Feb 14 '23 17:02

Gazler