views:

42

answers:

3

My data[l][m] contains 1,2,3,4,5 I'm trying to search for a particular number, say '2' in it. Is there a better way to do this?

for (var n = 0; n < data[l][m].length; n++) {
    if(data[l][m][n] == num){ // num is equal to '2'
        number = data[l][0];
        document.form.options[l-1] = new Option(number,number,true,true);
    }
}

And how about in: ['id1',['a',[1,2,3,4,5]],['b',[3,4,5,6,7]]]
Many thanks in advance.

+2  A: 

If you're already including jQuery, use $.inArray(), like this:

if($.inArray(num, data[l][m]) > -1) {
  number = data[l][0];
  document.form.options[l-1] = new Option(number,number,true,true);
}

The shorter vanilla JS version is a direct .indexOf() on the Array, but IE doesn't have this by default.

Nick Craver
+1 for `inArray`, but you're not getting `number`.
T.J. Crowder
@DGT: Note that all `inArray` is doing is what you've done; but as you're already using jQuery, might as well save some lines and debugging (and as a by-product it reuses the loop-invariant `data[l][m]` which I'd otherwise recommend you cache to a local).
T.J. Crowder
@TJCrowder - Missed the `number` bit, thanks!
Nick Craver
Thanks guys, but can I also use inArray to search within nested array such as ['id1',['a',[1,2,3,4,5]],['b',[3,4,5,6,7]]]?
DGT
@DGT - Yup, it's still just an array when you're iterating over it, regardless of where it's located.
Nick Craver
A: 

You could use indexOf, although it still has the same O(n) complexity as your for loop:

var pos = data[l][m].indexOf(num);
if (pos !== -1)
{
  // element was found
  number = data[l][0];
  document.form.options[l-1] = new Option(number,number,true,true);
}

Note, however, that older versions of IE do not have the indexOf method for Arrays.

Daniel Vandersluis
A: 

I have no major changes to recommend, but do have a couple tweaks to suggest. The first is to create a temporary reference to data[l] to reduce reading complexity by 1 level. This is a cosmetic change for the benefit of the coder. The other is cache the length of the array you are searching, which helps with performance. If you replace your for loop with the while loop as follows, you can also remove the comparison operations.

var layer1 = data[l];
var n = layer1[m].length;
while (n--) {
    if (layer1[m][n] == num) { // num is equal to '2' 
        number = layer1[0];
        document.form.options[l - 1] = new Option(number, number, true, true);
    }
}
lincolnk