0

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@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).
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 - Yup, it's still just an array when you're iterating over it, regardless of where it's located.
0

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.

Comments

0

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.