0

here is the code for making a 2d array to be used as a board for conways game of life in node.js. i am having a problem with displaying the board. the output looks like this.

['-','-','-'] 
['-','-','-']
['-','-','-']

however i want it to look like this

---
---
---

this is the code right now. Does anyone have any suggestions?

var createBoard = (width, height) => {
    board = [];
    row = [];
    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            row.push("-");
        }
        board.push(row);
        row =[];
    }
    return (board);
}

var displayBoard = (board) =>{
    for (var i = 0; i < board.length; i++) {
        console.log(board[i]);
    }
}

gameBoard = createBoard(3,3);
displayBoard(gameBoard);

2 Answers 2

2

You need to join the elements of the array to form a string.

var createBoard = (width, height) => {
    board = [];
    row = [];
    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            row.push("-");
        }
        board.push(row);
        row = [];
    }
    return (board);
}

var displayBoard = (board) => {
    for (var i = 0; i < board.length; i++) {
        console.log(board[i].join(""));
    }
}

gameBoard = createBoard(3, 3);
displayBoard(gameBoard);

Sign up to request clarification or add additional context in comments.

Comments

0

To fix your issue you should iterate over the array and add it to a string, like this:

var displayBoard = (board) =>{
   var buffer = '';
   for (var i = 0; i < board.length; i++) {
      for (var x = 0; x < board[i].length; x++) {
        buffer += board[i][x];
      }
      buffer += '\n';
   }
   console.log(buffer);
}

This should print it like this:

---
---
---

Comments

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.