22

I have a variable:

var code = "de";

And I have an array:

var countryList = ["de","fr","it","es"];

Could someone help me as I need to check to see if the variable is inside the countryList array - my attempt is here:

    if (code instanceof countryList) {
        alert('value is Array!');
    } 

    else {
        alert('Not an array');
    }

but I get the following error in console.log when it's run:

TypeError: invalid 'instanceof' operand countryList

BMW
  • 42,880
  • 12
  • 99
  • 116
ngplayground
  • 20,365
  • 36
  • 94
  • 173
  • 1
    -1 tag question with jquery if you want to get solution of jquery ...its missleading , second same answer is given before this answer y that is not marked as asnwer ...I wonder what going on SO if the same asnwer given before accepted answer not get accepted ... – Pranay Rana Nov 22 '12 at 10:09

7 Answers7

35

You need to use Array.indexOf:

if (countryList.indexOf(code) >= 0) {
   // do stuff here
}

Please not that it is not supported in and before IE8 (and possibly other legacy browsers). Find out more about it here.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
  • 2
    Note that `Array.indexOf` is not supported in IE8- (and possibly other legacy browsers). Use the shim at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility – David Hellsing Nov 22 '12 at 09:41
  • 1
    Implementing Array.indexOf is pretty trivial for older browsers, if that's a requirement. – beatgammit Nov 22 '12 at 09:46
23

jQuery has a utility function to find whether an element exist in array or not

$.inArray(value, array)

It returns index of the value in array and -1 if value is not present in array. so your code can be like this

if( $.inArray(code, countryList) != -1){
     alert('value is Array!');
} else {
    alert('Not an array');
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
5

You seem to be looking for the Array.indexOf function.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
complex857
  • 20,425
  • 6
  • 51
  • 54
5

instanceof is for checking if an object is of a certain type (which is a whole different topic). So instead of the code you wrote, you should lookup in the array. You can either check every element like this:

var found = false;
for( var i = 0; i < countryList.length; i++ ) {
  if ( countryList[i] === code ) {
    found = true;
    break;
  }
}

if ( found ) {
  //the country code is not in the array
  ...
} else {
  //the country code exists in the array
  ...
}

Or you can use the simpler method of using indexOf() function. Every array has an indexOf() function that loops up an element and returnns its index in the array. If it can't find the element, it returns -1. So you check the output of indexOf() to see if it has found anything in the array that matches your string:

if (countryList.indexOf(code) === -1) {
  //the country code is not in the array
  ...
} else {
  //the country code exists in the array
  ...
}

I would use the second algorithm because it is simpler. But the first algorithm is good too because it is more readable. Both have the same income, but the second one has better performance and is shorter. However, it is not supported in older browsers (IE<9).

If you are using the JQuery library, you may use the inArray() function which works in all browsers. It is the same as indexOf() and retuns -1 if it doesn't find the element you are looking for. So you can use it like this:

if ( $.inArray( code, countryList ) === -1) {
  //the country code is not in the array
  ...
} else {
  //the country code exists in the array
  ...
}
AlexStack
  • 16,766
  • 21
  • 72
  • 104
3

In jquery you can make use of

jQuery.inArray()-Search for a specified value within an array and return its index (or -1 if not found).

if ($.inArray('de', countryList ) !== -1) 
{
}

for javascript solution check existing How do I check if an array includes an object in JavaScript?

Array.prototype.contains = function(k) {
    for(p in this)
        if(this[p] === k)
            return true;
    return false;
}
for example:

var list = ["one","two"];

list.contains("one") // returns true
Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 1
    simple question y there is -1 ? please comment on this – Pranay Rana Nov 22 '12 at 10:08
  • 1
    I think whoever downvoted (not me), did it because it was originally tagged with just JavaScript and unable to assume he was using a library. Now however it is clear he wants JQuery, so +1 as correct answer. – dsgriffin Nov 22 '12 at 10:13
  • @user1394965 - problem is -1 happen after the answer get selected by OP – Pranay Rana Nov 22 '12 at 10:15
2

For a pure JavaScript solution you could just traverse the array.

function contains( r, val ) {
    var i = 0, len = r.length;

    for(; i < len; i++ ) {
        if( r[i] === val ) {
            return i;
        }
     }
     return -1;
}
Bruno
  • 5,772
  • 1
  • 26
  • 43
0

using jQuery

You can use $.inArray()

$.inArray(value, array)

return index of item or -1 if not found

Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59