totalnoob
totalnoob

Reputation: 2741

traversing through an array with nested loops in javascript

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


 

Upvotes: 0

Views: 60

Answers (1)

Steven Spungin
Steven Spungin

Reputation: 29109

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...

Upvotes: 2

Related Questions