0

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 4

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

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
Please refer to the documentation on RegExp developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
i tried with.. var pattern = new RegExp((male|female|xyz),"i"); var search = 'male'; if(pattern.test(search)) { //search found }
0

I think what you need is indexOf. Check this example to understand how to use it:

Determine whether an array contains a value

Comments

0

If you mean in an array you can use indexOf

var find = 'male';
var haystack = ['female', 'male', 'xyz'];

alert((haystack.indexOf(find) >= 0));

Comments

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!)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.