I am trying to make nested arrays that mimic a grid using for loops. I want it to look like this:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
I have been able to create one line of the array like so
[0, 0, 0]
using
var num = 3;
var arr = [];
for (var j = 0; j < num; j++) {
arr[j] = 0;
}
console.log(arr);
I stuck with how to implement nesting the second for loop around the first. My thought would be to push the finished output of the inner loop to the i index of of the outer loop. So something like
var num = 3;
var arr = [];
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
arr[j] = 0;
}
// some command here to push the completed output of the inner output to i index of the outer loop
}
console.log(arr);
I am on the right track with this? If not, where do I need to shift my thinking here? I haven’t been able to get a solution that produces the desired outcome yet.
You just needed to initialize the subarray for each set, then utilize both counters to place your '0'
var num = 3;
var arr = [];
for (let i = 0; i < num; i++) {
arr[i] = [];
for (let j = 0; j < num; j++) {
arr[i][j] = 0;
}
}
console.log(arr);