Among many Google Apps Script best practices, as for script performance improvement, it is recommended to minimise calls to other services:
Using JavaScript operations within your script is considerably faster than calling other services. Anything you can accomplish within Google Apps Script itself will be much faster than making calls that need to fetch data from Google's servers or an external server, such as requests to Spreadsheets, Docs, Sites, Translate, UrlFetch, and so on. Your scripts will run faster if you can find ways to minimize the calls the scripts make to those services.
As a result, when dealing with GAS on a spreadsheet, a common practice is to copy values from a sheet as a whole into a 2D array, do all manipulations on the array, then flush all data from array back to sheet.
Once you have copied all data from sheet into the 2D array, dealing with columns may be tricky, particularly with large column sets, therefore it could be handy to use a function that will extract/set data from the 2D array using A1 notation, as this allows to visually determine on the sheet what is the correct range, while using a Javascript transcoding function to identify columns and rows accordingly.
Without reinventing the wheel, I was wondering if someone wrote some code to extract data from a 2D array as a subarray, using a spreadsheet range A1 notation to reference the boundaries of the subarray.
For instance, assuming a custom function getRange
:
var SS = SpreadsheetApp.openById(myID); // open spreadsheet
var sheet = SS.getSheetByName("Test"); // get sheet
var sheetValues = sheet.getSheetValues(1,1,-1,-1); // copy all values from sheet to 2D array
// samples: how the function could be invoked to extract subarray using A1 notation
var subArray = getRange(sheetValues, "A2:A"); // returns a "column" from the array begin at row 2
subArray = getRange(sheetValues, "A2"); // returns a "cell" from the array (1,0)
subArray = getRange(sheetValues, "B2:D3"); // returns a 2D subarray
Similar to this
Edit:
I have copied the following code from another similar post and this works now that I have correctly set parameters:
var matrix = [
["a1", "b1", "c1", "d1"],
["a2", "b2", "c2", "d2"],
["a3", "b3", "c3", "d3"],
["a4", "b4", "c4", "d4"]
]
var startRow = 1
var startCol = 0
var endRow = 2
var endCol = 0
var section = matrix.slice(startRow, endRow + 1).map(i => i.slice(startCol, endCol + 1))
console.log(JSON.stringify(section))
I will further investigate on A1 transcoding!