Check if an Item exists in a multidimensional Array

Hello all,

The following code returns the index of an Item if it is found in a multidimensional array.
The problem with it is that if the item is not found it results in an error and stops executing the rest of my code.

I’ve tried to let it return a -1 index if not found but it keeps on telling that it is “undefined”

JSFiddle

myArray = [
    ["AA", "Walter", "White", "Albuquerque"],
    ["RY", "Skyler", "White", "Albuquerque"]
];

var test = "RY";

for (var i = 0; i < myArray.length + 1; i++) {
    if (myArray[i][0] === test) {
        var index = i;
        break;
    } 
}

alert(i);
alert("alert if not found");

Arrays start at 0, so doing myArray.length+1 is making it go out of bounds. Just take off the +1. This will get rid of the Uncaught TypeError: Cannot read property '0' of undefined error that you’re getting.

If you have the array var myArr = ['one', 'two', 'three'] the length is 3, but to access “three” you would reference myArr[2]. Essentially, you’re code is trying to look for it at myArr[3] and there is nothing there.

There are a number of other things wrong here, which technically work because of some weirdness in JS, but aren’t the right way to do things. var i in the loop is accessible outside of the loop, but generally should be considered out of scope, as well as index should be declared outside of the loop and alert(i) should be referencing alert(index) instead. But, this works in JS because of variable hosting, but it will probably not work if you ever move to another language and is a bad habit to get in to.

Not to mention that OP is using a reserved word for a variable name (test).

HTH,

:slight_smile:

1 Like

I know that arrays start at 0 but for some reason I added one (just to see what happens) :smile:
I must have forgot to remove it.

Thank you very much for your help and for clarifying things!

Didn’t know that. thanks!

1 Like

Be sure to check the developer console in your browser.

Here is a script that sorts out your problem areas and allows you to find the target string anywhere in your sub arrays.

<script type="text/javascript">
 var myArray = [
    ["AA", "Walter", "White", "Albuquerque"],
    ["Skyler", "White", "Albuquerque", "RY"]
  ];
var testIt="RY";
var i=0, k=0, indx=[], msg;
for ( i=0; i<myArray.length; i++) 
  { for ( k=0; k<myArray[i].length; k++)   
      { if (myArray[i][k] === testIt){ indx = [i,k]; break; }  
  }    }
if(typeof indx[0] == "undefined" || typeof indx[1] == "undefined"){ msg=("Not found"); }
else { msg="i= "+indx[0]+" k= "+indx[1]; }
alert(msg);
//  
</script>

Thanks AllanP This is very useful!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.