Reputation: 335
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.
Upvotes: 4
Views: 133
Reputation: 1725
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;
}
Upvotes: 5
Reputation: 1363
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;
}
Upvotes: 2