Search code examples
javascriptarraysmembership

testing for array membership in JS produces surprising results


I have the following lines of JS in a program...

            console.log(self.dataset[altAspect][altGroup] + " is the contents of the altGroup");
            console.log(answer + " is the answer to be checked");
            console.log('it is ' + (self.dataset[altAspect][altGroup].indexOf(answer) > -1) + ' that ' + answer + ' is a member of ' + self.dataset[altAspect][altGroup]);
            if (!self.dataset[altAspect][altGroup].indexOf(answer) > -1){                        
                self.wrongGroups.push(altGroup);
                console.log('added ' + altGroup + ' to the wrong groups!');
                self.altCount++;
            }

this logs the following to the console:

ginger,daisy is the contents of the altGroup  app.js:203:21
daisy is the answer to be checked  app.js:204:21
it is false that daisy is a member of ginger,daisy  app.js:205:21
added skinny to the wrong groups!  app.js:208:25

My question is, why is the above saying that "daisy" is not a member of ["ginger", "daisy"]? Obviously when I run [ "ginger", "daisy" ].indexOf("daisy") I should get 1 in return.


Solution

  • if you use [ "ginger", "daisy" ].indexOf("daisy") you got 1 as index value and

    if you use this [ "ginger", "daisy" ].indexOf(answer) you getting -1 as index value..

    so, it may arises due to some whitespace may occur in your variable answer

    you try to compare length of both...

    compare answer.length with "daisy".length or else try this,

    [ "ginger", "daisy" ].indexOf(answer.trim()) . probably you will notice issue while getting text length..