3

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.

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Adam, this is what I'd call a 'positive collaboration' ;-) thanks and +1 for the "complement to complement" !
This solution works like charme. I copied and pasted it and did exactly what I needed. My scripts running >100 times faster
4

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 ;)

1 Comment

wow. so complicated for such an easy action. what if i wanted to make a sub 3x3 array out of the IO_array? can you help me with some code on that? Thanks Serge.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.