1

I am having an array like this format

var aa = ["a","b","c","d","e","f"];

var categoryid = ["a","x","e","w","q","p"];

And I wants to check this list like this

for(var ii = 0; ii < aa .length; ii++){
iid += " && category != "+aa [ii];
}

Also I need to check condition like this,

if(categoryid != 0 iij) { 
    alert("value not present");
}

Here this condition is not working like this exactly. Here I need like this format

if(categoryid != 0 && categoryid != 'a') {
    alert("value not present");
}

Please help me..

8
  • Are you saying you want to check that category.id is not equal to any value within the array? Commented Sep 11, 2013 at 9:49
  • @dipesh, yes it is currect Commented Sep 11, 2013 at 9:51
  • what exactly you want to check and out of the above what is working and what not ? Commented Sep 11, 2013 at 9:51
  • What is with iij in the condition if(categoryid != 0 iij)? And also is it categoryid or category.id? Commented Sep 11, 2013 at 9:52
  • sorry did not recognise it Commented Sep 11, 2013 at 9:54

3 Answers 3

1

You can check if a value is in an array (or, in this case, not in an array) using the array's indexOf method (assuming newer browsers).

Alternatively, try this shim:

function in_array(array,value) {
    if( array.indexOf) return array.indexOf(value) > -1;
    for( var i=0, l=array.length; i<l; i++) {
        if( array[i] == value) return true;
    }
    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you're trying to say that you want to test that category.id is not equal to any value within the array then you can use the .indexOf() method:

if (categoryid != 0 && aa.indexOf(category.id) === -1) {
   alert("value not present");
}

Note that .indexOf() is not supported in IE8 and older, but MDN explains how to work around that.

1 Comment

@DipeshParmar That's just a typo.
0

Javascript can't be so dynamic, what you need is like below:

if(categoryid != 0 && aa.indexOf(category.id) == -1) {
  alert("value not present");
} 

4 Comments

It can be, when using eval() in one of its appearances.
@Sirko Yes, it can be. But we just don't use eval() :)
@Sirko - Friends don't let friends use eval(). (Actually I don't agree that eval() is always a bad idea, but I really don't think it's appropriate here.)
@nnnnnn Sure, this is not a valid usecase for eval() (but there are some). I just wanted to correct the statement "it is not possible".