Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if a variable is in an array? [duplicate]

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

like image 274
ngplayground Avatar asked Nov 22 '12 09:11

ngplayground


People also ask

How do you check if there are duplicates in an array java?

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.

How do you check if a number is repeated in an array in C?

for(int j = i + 1; j < length; j++) { if(arr[i] == arr[j]) printf("%d\n", arr[j]); }


2 Answers

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.

like image 100
dsgriffin Avatar answered Oct 06 '22 16:10

dsgriffin


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');
}
like image 23
Sukhdeep Singh Handa Avatar answered Oct 06 '22 15:10

Sukhdeep Singh Handa