• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 95
  • Last Modified:

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
Asked:
Isaac
2 Solutions
 
Kim WalkerWeb 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"));
}

Open in new window

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

Open in new window


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

Open in new window

0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now