javascript find if value is NOT IN array
Asked Answered
S

3

22

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
   }
});
Showbread answered 30/6, 2011 at 21:53 Comment(0)
D
40

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
   }
});
Dullish answered 30/6, 2011 at 21:54 Comment(6)
your code is wrong, !($.inArray(iBarCode, myArray) fails if the element is in position 0. you should use !!~($.inArray(iBarCode, myArray) instead.Geodesy
now my loop is not entering the if statement for any barcodes! the myArray is blank at the endShowbread
sadmicrowave, I wrote the if statement incorrectly, since inArray returns -1 if not found. I have updated the answer.Dullish
thank 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?Showbread
indexOf is not supported in IE. See this question. #1744810Dullish
Also -1 isn't supposed in some browsers, this can be set as 'undefined'.Erlineerlinna
S
9

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.

Shantishantung answered 30/6, 2011 at 21:58 Comment(1)
and if not using jquery, just use if( myArray.indexOf(iBarCode) === -1 ){ // do something else }Fluidics
R
0

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

Ratib answered 30/4, 2021 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.