Michael Z
Michael Z

Reputation: 3993

Check element presence in array

What is the simplest way too check is some element presence to array?

I have following code:

    var val = "1";
    var arr = ["1", "2"];
    if($.inArray(val, arr)) {
        console.log("I am in!")
    } else {
        console.log("I am NOT here :( ")
    }

but it prints "1" is NOT at ["1", "2"] array! Please open my eyes - what is the problem here?

Upvotes: 0

Views: 181

Answers (1)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

The $.inArray returns index of the matched element position which can range from 0 to (length - 1). So you should >= 0 as it is the first element it will be returning the index as 0.

var val = "1";
var arr = ["1", "2"];
if($.inArray(val, arr) >= 0) {
    console.log("I am in!")
} else {
    console.log("I am NOT here :( ")
}

Upvotes: 2

Related Questions