Let's take a closer look at the functionality of your code:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [i];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = [i+j];
}
}
console.log(myMatrix);
You may have inadvertently made a typo in your row
/ rows
variable name. Setting that aside...
Your line myMatrix[i]
is producing an array at position i
, which is then assigned to an array with the value of i
. This results in a strange combination where each "row" receives an array with its row number as the first value, something like this:
[[0], [1], [2], [3], [4]]
Subsequently, your inner loop appends a value to that array and sums up i+j
, but encloses it within an array, when that is not the desired outcome. Consequently, you end up with something along these lines:
[
[[0], [1], [2]], // i = 0
[[1], [2], [3]], // i = 1
[[2], [3], [4]], // i = 2
// ... etc
]
Furthermore, note that you are overwriting that initial [i]
anyhow, so it would be more appropriate to initialize it as an empty array []
.
The intended result should resemble the following structure:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j;
}
}
console.log(myMatrix);
Three modifications were made to your original code:
- Adjust
[i]
to simply []
, while maintaining consistency.
- Omit the array encapsulation from the
i+j
calculation, aiming solely for a value.
- When adding
i
, multiply by columns
to prevent resetting every iteration: (i*columns)+j
This amended script will yield a clean output, initiated from 0
. To commence from 1
, consider incrementing your value by one:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j+1;
}
}
console.log(myMatrix);