Search code examples
javascriptarraysfor-loopnested-loops

js how to make 2d array matrix with for loop and continue counting numbers on next row


I'm trying to make my 2d matrix to have numbers which continue on the new row

var myMatrix = [];

var row = 5;
var colom = 3;

for (var i = 0; i < rows; i++) {
  var toto = 1;
  myMatrix[i] = [i];
  for (var j = 0; j < colom; j++) {
    myMatrix[i][j] = [i + j];
  }

}

console.log(myMatrix);

I'm trying to make it print numbers like this:

123

456

789 and etc...

but without success:/

can someone help and also give a video or site with examples where i can learn more about that kind of stuff?


Solution

  • First, a look at what your code is doing:

    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 have a typo in your row/rows variable name. Ignoring that though...

    Your myMatrix[i] line is creating an array at i, which is then being set to an array with a value of i. Just this creates a wonky mash-up , where each "row" gets an array with it's row number as the first value, something like this:

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

    Your inner loop then adds a value to that array at the place and adds i+j together, but puts that inside of an array, which isn't what you want, so you get something like this:

    [
     [[0], [1], [2]], // i = 0
     [[1], [2], [3]], // i = 1
     [[2], [3], [4]], // i = 2
     // ... etc
    ]
    

    Also note that you are replacing that first [i] anyways, so don't set it like that, just make it an empty array [].

    What you want is something like this:

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

    There were three changes to your code:

    • Make the [i] and []. It doesn't hurt anything, but [i] also doesn't make sense.
    • Take the i+j part out of the array, you just want a value there.
    • When you add i, multiply it by columns so it doesn't reset every time: (i*columns)+j

    This will give you a nice output, starting with 0. If you want it start at 1, just add one to your value:

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