All of the mentioned functions below in this answer will output a 1 dimensional array, which I feel will be slightly more convenient to operate with.
Solution 1:
Just another way of obtaining a column or a row:
function getColumn(activeSheet, columnIndex) {
return activeSheet.getRange(1, columnIndex)
.getDataRegion(SpreadsheetApp.Dimension.ROWS)
.getValues()
.flat();
}
function getRow(activeSheet, rowIndex) {
return activeSheet.getRange(rowIndex, 1)
.getDataRegion(SpreadsheetApp.Dimension.COLUMNS)
.getValues()[0];
}
Note: This will only fetch data which are in the adjacent cells in the given direction.
Example: 1, 2, 3, blank, 4, blank, 5 ----- 4 and 5 will be skipped. Also, see getDataRegion(dimension)
.This is an ideal solution if you have no empty cells within the data region.
Solution 2:
Extending @itazzad's solution,
// JS object containing indices as keys and capital letters as value.
const INDEX_ALPHABET = Array.from(new Array(26))
.reduce((accumulatedObj, _, index) =>
(accumulatedObj[index + 1] = String.fromCharCode(index + 65), accumulatedObj), {});
// uses a1 notation
function getColumn(activeSheet, columnIndex) {
var columnA1Notation = INDEX_ALPHABET[columnIndex]
return activeSheet.getRange(columnA1Notation + ':' + columnA1Notation)
.getValues()
.flat();
}
// uses a1 notation
function getRow(activeSheet, rowIndex) {
return activeSheet.getRange(rowIndex + ':' + rowIndex)
.getValues()[0];
}
See getRange(a1Notation)
. I was not sure of what R1C1 notation and A1 notation meant, but this article helped a bit.
Solution 3:
If you believe getValues()
might be a expensive call and increases in time execution as the Range
increases in size, then check this out. Basically it gets the last row or column and uses it to reduce the Range
without omitting any relevant data.
function getRow(activeSheet, rowIndex) {
var lastColumn = activeSheet.getDataRange().getLastColumn()
return activeSheet.getRange(rowIndex, 1, 1, lastColumn)
.getValues()[0]
}
function getColumn(activeSheet, columnIndex) {
var lastRow = activeSheet.getDataRange().getLastRow()
return activeSheet.getRange(1, columnIndex, lastRow, 1)
.getValues()
.flat()
}
Note: If you want to get a slice of a row or column, check out getRange(row, column, numRows, numColumns)