You need to make use of a nested for loop:
So please have a look at my solution:
let grid = [
[1,2,3],
[4,5,6],
[7,8,9]
];
for (let x = 0; x < grid[0].length; x++) {
for (let y = 0; y < grid.length; y++) {
console.log(grid[y][x]);
}
}
This grid prints out the expected solution: 1, 4, 7, 2, 5, 8, 3, 6, 9?
Some explanation:
In this case we are using two different for-loops.
- the outer one for the X
for (let x = 0; x < 3; x++) {}
- the inner one for the Y
for (let y = 0; y < 3; x++) {}
Note: This will just work if the grid is rectangular because using grid[0].length will otherwise produce an error.
Edit: If you just want to use a single loop try something like this:
let grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (let i = 0 ; i < grid.length * grid[0].length ; i++)
console.log(grid[i % grid.length][parseInt(i / grid.length)]);