mrp
mrp

Reputation: 767

Javascript search in Array

I'Ve got a problem with the $.inArray function from JQuery (I also tried indexOf)

My Code:

var branches = circles[i].branches;
var counter = 0;
for (var j = 0; j < branches.length; j++) {

   var circle_branch = branches[j];
   var index = $.inArray( circle_branch, activeBranchSettings);
   if (index == -1)counter++;                   
}
if(counter == 0) circles[i].setMap(map);

So I'm working with the Google Maps API and I've a control panel with some categories (branches) where I toggle the Markers. Each circle (Marker) can have multiple branches and those ID's are attached to each circle. So I loop through the branches and want to find that ID in an other array (activeBranchSettings), every time there wasn't a match I increase a counter. If the counter is 0 in the end I toggle the circle on. So this tells which Markers should NOT be shown and which should.

Whether it'S the perfect way to solve it or not, the problem is that

  var index = $.inArray( circle_branch, activeBranchSettings);

return -1 everytime! The value IS at that point in the array and I tried to convert "circle_branch" into a string with .toString(), but still no change, Any ideas?

Upvotes: 1

Views: 201

Answers (2)

Bernie
Bernie

Reputation: 5055

These testcase is working well. So maybe a compare of the datatype (typeof(variable)) would be a step to find the issue

<script type="text/javascript">
    var arr = new Array('a', 'b', 'c', 'd');
    var look = new Array('d', 'b');

    for(var i=0; i<arr.length; i++)
    alert($.inArray( arr[i], look));
</script>

Upvotes: 1

Archer
Archer

Reputation: 5147

As per jQuery documentation inArray has the following syntax.

jQuery.inArray( value, array [, fromIndex ] )

Means value should come firt and array should come second. It's not quite clear form your example what is activeBranchSettings is it an array or searchable value?

Upvotes: 0

Related Questions