Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 648
Jo3la Avatar asked Jul 05 '12 14:07

Jo3la


People also ask

How do you push a two dimensional array?

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] .

What does push () method of the array do?

push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.

What is push () JS?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.

Can we push object in array?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.


1 Answers

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);     } } 
like image 155
Sirko Avatar answered Sep 24 '22 08:09

Sirko