Home > Blockchain >  How to create 2d array using "for" loop in Javascript?
How to create 2d array using "for" loop in Javascript?

Time:03-29

I need to write a program that creates a 2d array in variable "numbers" in rows (5) and columns (4). The elements of the array have to be consecutive integers starting at 1 and end at 20. I have to use "for" loop.

[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ],
[ 17, 18, 19, 20 ],

So I came up with that:

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i  ) {
    numbers [i] = [];
    for (let j = 0; j < columns; j  ){
        numbers  [i][j] = j   1;
    }
}
console.log(numbers); 

But the result of this is five identical rows, like this:

      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ]

Do you have any idea how to fix it? How to make second row starting from 5?

CodePudding user response:

Looks like in the second loop, you should do numbers [i][j] = j * i; instead

CodePudding user response:

Every time the outer for loop starts a new iteration, j is reset back to 0, which is why you keep getting rows starting with 1.

To fix this, you could declare a variable outside of the for loops that tracks the current number, and use that instead of j like so:

const numbers = [];
const columns = 4;
const rows = 5;
let currNum = 0;

for (let i = 0; i < rows; i  ) {
    numbers [i] = [];
    for (let j = 0; j < columns; j  ){
        currNum  ;
        numbers  [i][j] = currNum;
    }
}
console.log(numbers); 

CodePudding user response:

Here is some updated code. You need to add i*columns to every value

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i  ) {
    numbers[i] = [];
    for (let j = 0; j < columns; j  ){
        numbers[i][j] = j   1   (i*columns);
    }
}
console.log(numbers); 

  • Related