views:

53

answers:

3

I'm trying to find out the best way to check if an item is already in an array.

I have a number of checkboxes that belong to 1 of 5 groups. When a user clicks on one of these checkboxes, a second and third list that belong to one of the groups is written to the page.

What I'm trying to do is add these groups to an array, and once they're added, iterate through the array and add the second and third list.

var v = $(this).val();
// or this could be "something"

    if ($.inArray(v, _catArray)) {
        alert("it's here..");
    } else {
        alert("not in array");
    }

No matter what, this tells me that it IS in the array... even though it's not at all.

+5  A: 

jQuery has a $.inArray() method you can use.

Please note that $.inArray() returns -1 if it's not in the array, and the location if it is. It does not return a boolean.

Example:

if($.inArray("a", myArray) != -1){
    alert('In Array');
}
else{
    alert('Not In Array');
}
Rocket
+1  A: 

Might help to check out jQuery's inArray function.

var myArray = ['a','b','c'];
$.inArray('a', myArray);

var $cb1 = $(':checkbox#1');
var $cb2 = $(':checkbox#2');
var myObjArray = [$cb1, $cb2];
$.inArray($cb2, myObjArray);

This function will return the index of the array where the element was found, or if not found will return -1.

http://api.jquery.com/jQuery.inArray/

jenjenut233
A: 

If you don't want to be tied to jQuery for something thats very non DOM oriented, check out indexOf. If you have to support a browser that doesn't have the Javascript 1.6 array methods, just copy/paste the code on that page.

Angiosperm