How to find out if a given value is among some values? Similar to the IN operator in SQL or what you might expect from sets. Let's suppose set is {male,female,xyz}. I want to find if male is in the set.
4 Answers
The in operator does exist in JavaScript. But it checks whether a property exists on an object.
You can use an object hash or an array:
var values = {male: true, female: true, xyz: true}
var valueToSearch = 'female';
valueToSearch in values; //true
var values = ['male', 'female', 'xyz']
values.indexOf(valueToSearch) !== -1 // true
EDIT: Using a RegExp:
if(pattern.test(search)) {
//search found
}
3 Comments
user2450833
var pattern=new RegExp(male|female|xyz); var search="malee"; i want to know search is in pattern or not in terms of true false....in my example answer should be false
c.P.u1
Please refer to the documentation on RegExp developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
user2450833
i tried with.. var pattern = new RegExp((male|female|xyz),"i"); var search = 'male'; if(pattern.test(search)) { //search found }
I think what you need is indexOf. Check this example to understand how to use it:
Comments
If you mean in an array you can use indexOf
var find = 'male';
var haystack = ['female', 'male', 'xyz'];
alert((haystack.indexOf(find) >= 0));
Comments
Object
var objNames = {
"Michigan": "MI",
"New York": "NY",
"Coffee": "yes, absolutely"
};
Array
var arrNames = [
"Michigan", "New York", "Coffee"
]
Function
function isIn(term, list) {
var i, len;
var listType = Object.prototype.toString.call(list);
if (listType === '[object Array]') {
for (i = 0, len = list.length; i < len; i++) {
if (term === listType[i]) { return true; }
}
return false;
}
if (listType === '[object Object]') {
return !!list[term]; // bang-bang is used to typecast into a boolean
}
// What did you sent to me?!
return false;
}
Usage
var michiganExists = isIn('Michigan', objNames); // true
Note
I didn't use indexOf because the op didn't mention browser support, and indexOf doesn't work with all versions of Internet Explorer (gross!)