• Status: Solved
• Priority: Medium
• Security: Public
• Views: 121

# indexOf() 2d array value

How can I get the array index of a value in a 2d array?
Here's my jsfidle
https://jsfiddle.net/isogunro/2h3wf4q4/
0
Isaac
2 Solutions

Web Programmer/TechnicianCommented:
Your multi-dimensional array definition is generating an error. You cannot define ary[0][0] until you have established that ary[0] is an array. This is true for ary[1] through ary[4] also. Once you have properly defined your multi-dimensional array, you would have to search each tier of the array to find the index of "Boat."
``````var ary = [];

ary[0] = ["Car","Boat"];
ary[1] = ["Car","Boat"];
ary[2] = ["Car","Boat"];
ary[3] = ["Car","Boat"];
ary[4] = ["Car","Boat"];

for (var i in ary) {
console.log(ary[i].indexOf("Boat"));
}
``````
0

Commented:
To expand on Kim's solution.
You can declare the array upfront like so
``````var ary = [[],[],[],[],[]];
``````

Output changed a bit to show array and index
``````var ary = [[],[],[],[],[]];

ary[0][0] = "Car";
ary[0][1] = "Boat";
ary[1][0] = "Car";
ary[1][1] = "Boat";
ary[2][0] = "Car";
ary[2][1] = "Boat";
ary[3][0] = "Car";
ary[3][1] = "Boat";
ary[4][0] = "Car";
ary[4][1] = "Boat";

for(var i in ary){
var aryIndex = ary[i].indexOf("Boat");
// Added array and index in array
console.log('Array[' +i + '] index: ' + aryIndex);
}
``````
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.