1

I can't figure out what I'm doing wrong. Why is this not returning true? What am I missing

var suppliers = ["13419", "12999", "13992"];
var id = 13419;

if ($.inArray(id, suppliers) != -1) {
  console.log('duplicate');
} else {
  console.log('no dupe');
}
1
  • 1
    You're comparing string with int Commented May 10, 2016 at 13:55

4 Answers 4

1

You need to change first element to string so the value you are searching for and values in array are same datatype

var suppliers = ["13419", "12999", "13992"];
var id = 13419;

$.inArray(String(id), suppliers) != -1 ? console.log('duplicate') : console.log('no dupe');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Other option is to change every element inside your array to number

var suppliers = ["13419", "12999", "13992"].map(e => {return parseInt(e)});
var id = 13419;

$.inArray(id, suppliers) != -1 ? console.log('duplicate') : console.log('no dupe');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

2 Comments

Thank you! How can I implement this in my real life example where I get the id from an element value? because I can't just add ' ' to the variable
Could you create fiddle as example.
0

your id is integer that is

 var id = 13419;

while your arry contain strings that is

 var suppliers = ["13419", "12999", "13992"];

so give it in string like

 var id = "13419";

Comments

0

jQuery uses === to determine if items are equal. So it takes in account variable type, so You must change id type before checking:

if ($.inArray(id.toString(), suppliers) != -1) {
  console.log('duplicate');
} else {
  console.log('no dupe');
}

Or create Your own function:

function customInArray(needle, heystack) {
    for (item in heystack) {
            if (needle == heystack[item]) {
                return item; 
        }
    }

    return -1;
}

Comments

0

Try to change either supplier or id datatype.

var suppliers = [13419, 12999, 13992];

Check this JSFiddle

Comments

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.