[javascript] 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?

This question is related to javascript arrays for-loop multidimensional-array push

The answer is


The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).

In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.

 function arraySection(arr, r1, c1, rLength, cLength) {      
   rowMax = arr.length;
    if(isNaN(rowMax)){rowMax = 1};
   colMax = arr[0].length;
   if(isNaN(colMax)){colMax = 1};
   var r2 = r1 + rLength - 1;
   var c2 = c1 + cLength - 1;

   if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 || 
     r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax || 
   (c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
        throw new Error(
        'arraySection: invalid input')       
        return;
     };
   var newArr = [];

// Case 1: extracted section is a column array, 
//          all elements are in the same column
 if (c1 == c2){
   for (var i = r1; i <= r2; i++){ 
         // Logger.log("arr[i][c1] for i = " + i);
         // Logger.log(arr[i][c1]);
     newArr.push([arr[i][c1]]); 
     };
    };  

// Case 2: extracted section is a row array, 
//          all elements are in the same row
  if (r1 == r2 && c1 != c2){
    for (var j = c1; j <= c2; j++){ 
      newArr.push(arr[r1][j]); 
      };
   };  

// Case 3: extracted section is a 2x2 section 
    if (r1 != r2 && c1 != c2){     
     for (var i = r1; i <= r2; i++) {
          rowi = [];
       for (var j = c1; j <= c2; j++) {
          rowi.push(arr[i][j]);
        }
       newArr.push(rowi)
      };
    };
   return(newArr);
  };

Iterating over two dimensions means you'll need to check over two dimensions.

assuming you're starting with:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]; //don't forget your semi-colons

You want to expand this two-dimensional array to become:

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],
];

Which means you need to understand what the difference is.

Start with the outer array:

var myArray = [
    [...],
    [...],
    [...]
];

If you want to make this array longer, you need to check that it's the correct length, and add more inner arrays to make up the difference:

var i,
    rows,
    myArray;
rows = 8;
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill
        myArray.push([]);
    }
}

The next step requires iterating over every column in every array, we'll build on the original code:

var i,
    j,
    row,
    rows,
    cols,
    myArray;
rows = 8;
cols = 7; //adding columns in this time
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array (row)
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill
        myArray[i] = [];
    }
    row = myArray[i];
    for (j = 0; j < cols; j += 1) {
        //check if the index exists in the inner array (column)
        if (!(i in row)) {
            //if it doesn't exist, we need to fill it with `0`
            row[j] = 0;
        }
    }
}

you are calling the push() on an array element (int), where push() should be called on the array, also handling/filling the array this way makes no sense you can do it like this

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


for (var i = r; i < rows - 1; i++)
{

  for (var j = 0; j < cols; j++)
  {
      col.push(0);
  }
}

you can also combine the two loops using an if condition, if row < r, else if row >= r


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

var rows = 8;

var cols = 7;


for (var i = 0; i < rows; i++)

{

 for (var j = 0; j < cols; j++)

 {
    if(j <= c && i <= r) {
      myArray[i][j] = 1;
    } else {
      myArray[i][j] = 0;
    }
}

}

Create am array and put inside the first, in this case i get data from JSON response

$.getJSON('/Tool/GetAllActiviesStatus/',
   var dataFC = new Array();
   function (data) {
      for (var i = 0; i < data.Result.length; i++) {
          var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
          dataFC.push(serie);
       });

In your case you can do that without using push at all:

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

var newRows = 8;
var newCols = 7;

var item;

for (var i = 0; i < newRows; i++) {
    item = myArray[i] || (myArray[i] = []);

    for (var k = item.length; k < newCols; k++)
        item[k] = 0;    
}

You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols:

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

var rows = 8;
var cols = 7;

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array

Examples related to push

Best way to "push" into C# array Firebase: how to generate a unique numeric ID for key? Why does Git tell me "No such remote 'origin'" when I try to push to origin? Unknown SSL protocol error in connection Git push rejected "non-fast-forward" How to add multiple files to Git at the same time git push to specific branch Declare an empty two-dimensional array in Javascript? What does '--set-upstream' do? fatal: 'origin' does not appear to be a git repository