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.
Asked
Active
Viewed 68 times
0

David Hoerster
- 28,421
- 8
- 67
- 102

user2450833
- 69
- 6
4 Answers
1
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
}

c.P.u1
- 16,664
- 6
- 46
- 41
-
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 – user2450833 Aug 23 '13 at 12:28
-
Please refer to the documentation on RegExp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp – c.P.u1 Aug 23 '13 at 12:40
-
i tried with.. var pattern = new RegExp((male|female|xyz),"i"); var search = 'male'; if(pattern.test(search)) { //search found } – user2450833 Aug 23 '13 at 12:41
0
I think what you need is indexOf
. Check this example to understand how to use it:
0
If you mean in an array you can use indexOf
var find = 'male';
var haystack = ['female', 'male', 'xyz'];
alert((haystack.indexOf(find) >= 0));

Oskar Hane
- 1,824
- 13
- 8
0
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!)

kmatheny
- 4,042
- 1
- 19
- 12