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.

3
  • 2
    You need to create a new array for every row. Currently your board refers to the very same array 5 times.
    – Bergi
    Commented Mar 2, 2016 at 17:34
  • 1
    Also you should use local variables
    – Bergi
    Commented Mar 2, 2016 at 17:35
  • See stackoverflow.com/questions/16512182/…, and many other similar questions.
    – user663031
    Commented Mar 2, 2016 at 18:15

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.