0

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);


 

1
  • grid[i][grid.length - i - 1] Commented Aug 22, 2018 at 17:02

1 Answer 1

2

This will work for diag.

for (let i = 0; i < grid.length; i++) {
  // grid[i][i]
}

You can traverse the 4 diagonals by using grid.length-1-i for various indexes.

  // grid[grid.length-1-i][i] // etc...

This will give you 3,5,7

  // grid[i][grid.length-1-i] // etc...
Sign up to request clarification or add additional context in comments.

5 Comments

It should be a ; instead of a , in your for statement.
that magic value of length-1-i, how did you come up with that?
@Derek朕會功夫 I need to stop answering questions that need code on my phone... Thanks!
how do I get 159 with this?
grid[i][i] will return 0,0 1,1 and 2,2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.