2

I have a dictionary of strings to arrays of strings: {"a":["b", "c"]}. When indexing into the dictionary, I get an array of strings back, but checking if any string is in this array always returns false. Here is the code setup:

var dict = {
    "first":["a", "b", "c"]
}
if("a" in dict["first"]){
    // Never hits this line
    console.log("Found a!");
}

I'm pretty new to Javascript so I may be missing something about the setup of a dictionary object, but it seems pretty straightforward and I have professional experience in a few C languages so it is fairly disconcerting that this doesn't work. What is wrong here?

Dagrooms
  • 1,507
  • 2
  • 16
  • 42
  • The `in` operator checks for properties, like `"first" in dict` or `"0" in dict.first`. You want to check whether the array [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) an element – Bergi Apr 26 '16 at 04:13
  • The supposed "duplicate" question is not the same! – Dagrooms Apr 26 '16 at 04:20
  • @ Dagrooms: How does any of [these answers](http://stackoverflow.com/q/237104/1048572) not help you to check whether a string is in an array? Whether the array is part of a dictionary does absolutely not matter for your question. Or are you actually asking why the `in` operator doesn't do what you think it should do? – Bergi Apr 26 '16 at 04:26

2 Answers2

3

The in operator returns true if the specified property is in the specified object, Taken from here.

a is not a property it's an array value, array index is act as property and 0 in dict["first"] will be true here. So here you can use indexOf()

var dict = {
  "first": ["a", "b", "c"]
}
if (dict["first"].indexOf("a") > -1) {
  console.log("Found a!");
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    What a life saver. It was marked as duplicate but the duplicate question was not nearly the same answer, and I don't want to use jquery in this application. – Dagrooms Apr 26 '16 at 04:18
0

try this. this will work to you.

var dict = {
    "first":["c", "b", "a"]
};
console.log(dict.first);
for( var x in dict.first){

    if(dict.first[x]=="a")
    {
     console.log("index of a :"+ x);
     break;
    }
}
}
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52