Reputation: 958
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.
Upvotes: 0
Views: 962
Reputation: 51861
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);
Upvotes: 1