Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2d subarray index google script

I have 2D array question in google spreadsheet using app script.

I know to get make the code fastest, I'm supposed to use as few get and set functions as possible. So I'm trying to read a whole sheet into an 2D array first then referencing parts of it. Except I'm not sure how to reference the 2D array once it's in.

Here is what i have done so far.

var ss = SpreadsheetApp.getActiveSpreadsheet()
var COMPANYIOSheet=ss.getSheetByName("Sheet1"); 
var IO_array= COMPANYIOSheet.getRange("A1:c10").getValues();

I want to do something like:

var subarray=IO_array[3:5][1];

but that doesn't work. I can only seem to reference just one point ie:

var subarray=IO_array[3][1];

How do i slice into a sub 2D array?

Thanks.

like image 421
jason Avatar asked May 30 '26 01:05

jason


2 Answers

How do i slice into a sub 2D array?

By using slice(). ;-)

var subarray=IO_array.slice(2, 5);

Then you can reference subarray[i][1]. If you needed to create a new array with only the "second column", you would need to use some iteration.


edit: to add to Serge's addition, and in reply to your comment, here is a general way for returning a 2D sub-array from an array:

function slice2d(array, rowIndex, colIndex, numRows, numCols) {
  var result = [];
  for (var i = rowIndex; i < (rowIndex + numRows); i++) {
    result.push(array[i].slice(colIndex, colIndex + numCols));
  }
  return result;
}
like image 97
AdamL Avatar answered May 31 '26 15:05

AdamL


As a complement to Adam's answer, in your example IO_array[0] is row 1, IO_array[1] is row 2 etc..., each of them being a 1 dimension array. So the 'rows' are pretty easy to manage.

As for the columns, as Adam suggested you will have to iterate, here is a possible example :

var col = new Array()
for(i=0;i<IO_array.length;++i){
  col.push(IO_array[i][0] ;// taking index 0 means I'll get column A of each row and put it in the new array
}

hoping both answers will make it clear enough ;)

like image 25
Serge insas Avatar answered May 31 '26 14:05

Serge insas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!