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
user3718511
3451 gold badge4 silver badges17 bronze badges
-
What is it that you are trying to achieve?tdranv– tdranv2020年08月05日 06:48:23 +00:00Commented 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.user3718511– user37185112020年08月05日 06:49:55 +00:00Commented Aug 5, 2020 at 6:49
-
Could you elaborate on the pattern?Jerome– Jerome2020年08月05日 06:50:33 +00:00Commented 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]user3718511– user37185112020年08月05日 06:51:46 +00:00Commented Aug 5, 2020 at 6:51
-
1is there a particular pattern you want in calling the column number or it could be just random?Karl L– Karl L2020年08月05日 06:52:12 +00:00Commented Aug 5, 2020 at 6:52
2 Answers 2
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
Karl L
1,7251 gold badge9 silver badges11 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
catcon
1,3641 gold badge12 silver badges19 bronze badges
lang-js