I've never really understood multi dimensional arrays and how to move through them until recently.
so far, I've figured out how to go through a 2D array horizontally, vertically and diagonally automatically without hardcoding any numbers on a simple function to help me understand nested loops better.
an array is created with all the possible sequences, but it's the diagonal on the right (3,5,7) that I can't seem to conceptualize how to loop to and through.
any pointers?
is there a smarter way of doing all this?
const grid = [
[1,2,3],
[4,5,6],
[7,8,9]
]
const coordinates = grid => {
const arr = [];
// get horizontals
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid.length; j++) {
arr.push(grid[i][j]);
// horizontals
// grid[i][j]
// grid[0][0]
// grid[0][1]
// grid[0][2]
// grid[1][0]
// grid[1][1]
// grid[1][2]
// grid[2][0]
// grid[2][1]
// grid[2][2]
}
}
// get verticals
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid.length; j++) {
arr.push(grid[j][i]);
// verticals
// grid[j][i]
// grid[0][0]
// grid[1][0]
// grid[2][0]
// grid[0][1]
// grid[1][1]
// grid[2][1]
// grid[0][2]
// grid[1][2]
// grid[2][2]
}
}
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid.length; j++) {
if (i === j) arr.push(grid[i][j])
// grid[0][0]
// grid[1][1]
// grid[2][2]
}
}
console.log(arr)
}
coordinates(grid);