back arrow

Array Directional technique

04 - 08 - 2024

When working on a 2 dimentionals array, we often need to move around the array in different directions. There is a simple technique that is very useful. Let’s say we have this chess board array:

const board = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

and let’s say that we are at the center of the board which is 5, the position is [1, 1]. We can move around the board in 4 directions: up, down, left, right. The reason for the order is that this is the order of CSS shorthand property (E.g: margin: 1px 2px 3px 4px with up: 1px, right: 2px, down: 3px, left: 4px). Let’s print out values for these cells around our starting point.

const startRow = 1;
const startCol = 1;
const directions = [[-1, 0], [0, 1], [1, 0], [0, -1]];

for (let i = 0; i < directions.length; i += 1) {
  const [row, col] = directions[i];

  const curRow = startRow + row;
  const curCol = startCol + col;

  console.log(board[curRow][curCol]);
}

The result after running the code above on the terminal would look like this

2
6
8
4