Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access 2D array using single for loop in JavaScript?

Tags:

javascript

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.

like image 429
user3718511 Avatar asked Mar 02 '23 04:03

user3718511


1 Answers

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;              
     }
like image 159
Karl L Avatar answered Mar 07 '23 20:03

Karl L