javascript find if value is NOT IN array javascript find if value is NOT IN array arrays arrays

javascript find if value is NOT IN array


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


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.


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