4

I have a 2D array which has 10 rows and 10 columns and I want to access a column's element from each row like this:

myArray[0][9]
myArray[1][4]
myArray[2][5]
myArray[3][9]
myArray[4][5]
myArray[5][9]
myArray[6][8]
myArray[7][9]
myArray[8][7]; 
myArray[9][8] 

The code that I have used:

for(var i=0; i<theatregoers.length; i++)
 {
 myArray[i][9].position=true;
 
 
 }

Note: I do not have any idea how to change column numbers like this each time when loop run. I do not want to use the nest loop, just using a single loop.

MLavoie
9,91641 gold badges42 silver badges58 bronze badges
asked Aug 5, 2020 at 6:45
5
  • What is it that you are trying to achieve? Commented Aug 5, 2020 at 6:48
  • @tdranv thanks for ur response, actually I want to access column of each arrow according to the pattern that I mentioned above. Commented Aug 5, 2020 at 6:49
  • Could you elaborate on the pattern? Commented Aug 5, 2020 at 6:50
  • @Jerome myArray[0][9] myArray[1][4] myArray[2][5] myArray[3][9] myArray[4][5] myArray[5][9] myArray[6][8] myArray[7][9] myArray[8][7] myArray[9][8] Commented Aug 5, 2020 at 6:51
  • 1
    is there a particular pattern you want in calling the column number or it could be just random? Commented Aug 5, 2020 at 6:52

2 Answers 2

5

You can do something like this. put the column indexes/number in an array like:

 let colArray = [9,4,5,9,5,9,8,9,7,8] 
 
 for(var i=0; i<myArray.length; i++){ 
 myArray[i][colArray[i]].position=true; 
 }
answered Aug 5, 2020 at 6:55
Sign up to request clarification or add additional context in comments.

Comments

2

You can loop your array like this

var row = 10;
var column = 10;
for (var i = 0; i < row * column; i++) {
 myArray[Math.floor(i / row)][i % column].position = true;
}
answered Aug 5, 2020 at 6:49

2 Comments

The OP asked for an arbitrary pattern for the second index, so this answer is incorrect.
@Avius: agree, OP added more info later in the comment

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.