Home > OS >  Error when trying to use push into a 2d array
Error when trying to use push into a 2d array

Time:01-19

I'm trying to push a value into a 2d array but I'm getting the error:

Cannot read property 'push' of undefined

Here's a MWE of my code:

var saida = new Array()
for (i in dbInfo){
  saida[i].push(i)
}

Where dbInfo is a range in my sheet, but can be replaced by any other range for this example. I need the output to be a 2d array so I can work out the values into the sheet.

CodePudding user response:

If you just created the array the array is empty. So saida[n] will be undefined no matter what value n has.

You need to first create it. Then you can push into it.

Maybe something like this? Not sure what you need.

var saida = new Array()
for (i in dbInfo){
  saida[i]=[]
  saida[i].push(i)
}

CodePudding user response:

You will need to define your array to 2d Eg: int[,] arr= new string[3, 2];

You will need to iterate twice.

for(int col1 = 0; col1 < arr.GetLength(0); col1  ){
   for(int row1 = 0; row1 < arr.GetLength(1); row1  )
   { 
     arr[col1,row1] =  2; 
   }
 }

CodePudding user response:

If dbInfo is an object of type Range from the Sheet, then the returned array after using getValues is already a 2D array so a simple assignment will suffice:

function addData() {
  // your other code
  let dbInfoVals = dbInfo.getValues();
  let saida = dbInfoVals;
  console.log(saida)
}

However, if dbInfo is a 1D array, transforming into a 2D one can be done by using the splice method in JavaScript:

function addData() {
  // your other code
  let saida = [];
  while (dbInfo.length){ 
    saida.push(dbInfo.splice(0, 2));
  }
  console.log(saida);
}

The second parameter of splice will give you the number of columns, so you might need to adjust this to match your range accordingly.

Reference

  •  Tags:  
  • Related