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
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.
for(int j = i + 1; j < length; j++) { if(arr[i] == arr[j]) printf("%d\n", arr[j]); }
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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With