Solved

indexOf() 2d array value

Posted on 2016-10-20
2
39 Views
Last Modified: 2016-10-26
How can I get the array index of a value in a 2d array?
Here's my jsfidle
https://jsfiddle.net/isogunro/2h3wf4q4/
0
Comment
Question by:Isaac
2 Comments
 
LVL 21

Accepted Solution

by:
Kim Walker earned 350 total points
ID: 41853116
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
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 150 total points
ID: 41853414
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now