0

I'm trying to loop through a list of numbers and check if that number is part of another list of numbers using jQuery.each and jQuery.inArray. jQuery.inArray does not seem to be behaving as expected.

Here is my code:

var some_numbers = [1, 2];
var more_numbers = [0, 1, 2];

$.each(more_numbers, function(index, value) {
  if($.inArray(value, some_numbers)) {
    console.log(value);
  }
});

console.log('Some Numbers:');
console.log(some_numbers);

Here is the resulting console output:

0
2
Some Numbers:
[1, 2]

Will someone please help? This is maddening.

Edit: Problem solved! Changed my condition to this:

if($.inArray(value, some_numbers) !== -1)

Thanks everyone!

3
  • I can't accept the answer for another 7 minutes, according to the dialog that appeared when I attempted to do so. Commented Nov 29, 2010 at 14:19
  • Yes, but you should accept answers to your other questions. EDIT Looking through them, maybe you shouldn't; they don't have great answers. Commented Nov 29, 2010 at 14:21
  • Yeah, I just went back through and accepted what I felt qualified as a decent answer or at least what was closest to the solution that I ended up going with. Thanks again for your quick response to this question. Commented Nov 29, 2010 at 14:27

1 Answer 1

3

$.inArray returns an index, not a boolean.

To check whether the element was found, you need to check whether it's >= 0.

Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful. Added to the condition "!== -1" and this solved my problem. Thank you!

Your Answer

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.