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
 }
});
asked Jun 30, 2011 at 21:53

3 Answers 3

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
 }
});
answered Jun 30, 2011 at 21:54
Sign up to request clarification or add additional context in comments.

6 Comments

your code is wrong, !($.inArray(iBarCode, myArray) fails if the element is in position 0. you should use !!~($.inArray(iBarCode, myArray) instead.
now my loop is not entering the if statement for any barcodes! the myArray is blank at the end
sadmicrowave, I wrote the if statement incorrectly, since inArray returns -1 if not found. I have updated the answer.
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?
indexOf is not supported in IE. See this question. stackoverflow.com/questions/1744310/…
|
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.

answered Jun 30, 2011 at 21:58

1 Comment

and if not using jquery, just use if( myArray.indexOf(iBarCode) === -1 ){ // do something else }
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

answered Apr 30, 2021 at 13:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.