Home > Back-end >  Accessing column value in 2d array not returning expected value
Accessing column value in 2d array not returning expected value

Time:07-19

I am building a chess board with React and I have the board grid all laid out with a 2d array like such:

let board = [
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
];

The design is such that the squares will hold state of what piece is on it instead of having each piece maintain state of what square it is on. To move the pieces, I will first need to store the square's current position in the array on a click and then check the second squares position and state to see if a move is valid.

For example, if I wanted to make the move E7 to E5, that would be board[6][4] to board[4][4]. For those unaware, chess uses letters for the columns and numbers for the rows. I hard coded in the initial board state so the app looks like this when rendered:

enter image description here

Now when I try to console log each squares positional value, the row value logs as expected but the column values are incorrect. For rows 2 through 7, column value is logged as 0. For rows 1 and 8, the column value logs as expected for the first 5 values but then starts to repeat. Here is my code and a screen shot of the console log:

const Board = () => {

  //Irrelevant state stuff

  return (
    <div>
      <div className='board-cont'>
        {board.map((row) => {
          return row.map((col) => {
            return (
              <div
                className='board-sqr'
                onClick={() =>
                  console.log(
                    `Index of row ${board.indexOf(row)} 
                    \n Index of column ${row.indexOf(col)}`
                  )
                }
              >
                {col}
              </div>
            );
          });
        })}
      </div>
    </div>
  );
};

enter image description here

I think this has to do with the fact that I am using the indexOf method which is probably returning the first index with the given value. However, I am unsure of how to capture the column value correctly. How should I go about this? Here is the codesandbox to my code.

CodePudding user response:

Why not use indexes from map?

return (
    <div>
      <div className='board-cont'>
        {board.map((row, y) => {
          return row.map((col, x) => {
            return (
              <div
                className='board-sqr'
                onClick={() =>
                  console.log(
                    `Index of row ${y} 
                    \n Index of column ${x}`
                  )
                }
              >
                {col}
              </div>
            );
          });
        })}
      </div>
    </div>
  );

CodePudding user response:

You can use the second argument of the Array.map((element, elementIndex) => {}) callback function. It gives the index of the current element.

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

  • Related