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”
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.