Search code examples
javascriptarraysfor-loopmultidimensional-arraypush

push() a two-dimensional array


I'm trying to push to a two-dimensional array without it messing up, currently My array is:

var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]

And my code I'm trying is:

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;
var cols = 7;

for (var i = r; i < rows; i++)
{
    for (var j = c; j < cols; j++)
    {
        myArray[i][j].push(0);
    }
}

That should result in the following:

var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]

But it doesn't and not sure whether this is the correct way to do it or not.

So the question is how would I accomplish this?


Solution

  • You have some errors in your code:

    1. Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
    2. You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.

    One correct, although kind of verbose version, would be the following:

    var r = 3; //start from rows 3
    
    var rows = 8;
    var cols = 7;
    
    // expand to have the correct amount or rows
    for( var i=r; i<rows; i++ ) {
      myArray.push( [] );
    }
    
    // expand all rows to have the correct amount of cols
    for (var i = 0; i < rows; i++)
    {
        for (var j =  myArray[i].length; j < cols; j++)
        {
            myArray[i].push(0);
        }
    }