0

I'm trying to make a nested array with parameters that accepts 2 numbers as arguments that will be used to create the dimensions of a board.

In the following code, I would expect a 5X5 nested array to be printed, but instead am getting a 5x15 nested array.

function NestedArray(x,y) {
    rows = [];
    cells = [];
    board = [];
    for (var i = 0; i < x; i++) {
        for (var j = i; j < y; j++) {
           rows.push(cells); 
        }
        board.push(rows);
    }
    console.log(board);
}

NestedArray(5,5);

Please forgive any formatting errors, I'm new to JS.

rrk
  • 15,677
  • 4
  • 29
  • 45
Jessie Richardson
  • 938
  • 2
  • 9
  • 24
  • 2
    You need to create a new array for every row. Currently your board refers to the very same array 5 times. – Bergi Mar 02 '16 at 17:34
  • 1
    Also you should use [local `var`iables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) – Bergi Mar 02 '16 at 17:35
  • See http://stackoverflow.com/questions/16512182/how-to-create-empty-2d-array-in-javascript, and many other similar questions. –  Mar 02 '16 at 18:15

1 Answers1

1

In the first loop you need to create row and push it to the board. In the second loop you need to create cell and push it to the current row:

function NestedArray(x,y) {
    board = [];
    for (var i = 0; i < x; i++) {
        var arr = []; // create row
        board.push(arr);
        for (var j = 0; j < y; j++) {
           arr.push([]); // create and push cell to row
        }
    }
    console.log(board);
}

NestedArray(5,5);
madox2
  • 49,493
  • 17
  • 99
  • 99