How can I store a range of cells to an array? - google-apps-script

If I have a list of data in cells A1:A150 (but the amount can vary), is there a way to push that into an array without looking at each cell individually to determine if it is empty? I exceed my execution time by doing this and I need a faster way to store the data and stop when it hits an empty cell.
Below is how I currently do it:
for (var i = 1; i < 500; i++) {
if(datasheet.getRange("A" + i).getValue() == ""){
break;
}
else{
addedlist_old.push(datasheet.getRange("A" + i).getValue())
}

If you're using only one column, I'd suggest:
// my2DArrayFromRng = sh.getRange("A2:A10").getValues();
var my2DArrayFromRng = [["A2"],["A3"],["A4"],["A5"],[],[],["A8"],["A9"],[]];
var a = my2DArrayFromRng.join().split(',').filter(Boolean);
The methods .join() and .split(',') together convert the 2D array to a plain array (["A2","A3","A4","A5",,,"A8","A9",]).
Then the method .filter(Boolean) strips the empty elements. The code above returns [A2, A3, A4, A5, A8, A9].

Try this:
var sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
var lastRow = sheet.getLastRow();
var data = sheet.getRange(1, 1, lastRow, 1).getValues(); //getRange(starting Row, starting column, number of rows, number of columns)
for(var i=0;i<(lastRow-1);i++)
{
Logger.log(data[0][i]);
}
the variable data stores all the cells of column A.
Cell A1 is stored in data[0][0], cell A2 is stored in data[0][1], cell A3 is stored in data[0][2] and so on.
The getRange(starting Row, starting column, number of rows, number of columns) is a batch operation so it is much faster when you have a large dataset.

If you don't have empty cells in between it's actually pretty easy.
var lastRow = sheet.getLastRow();
var array = sheet.getRange('A1:A' + lastRow).getValues();
If you need to weed out empty entries after that, you can use a for statement, or to be faster, filter like an earlier answer shows.
var filteredArray = array.filter(function(n){ return n != '' });
The main difference between this answer and the one posted earlier that I mentioned is that getValues() will give you an array.
I've tested this and it works in google apps script, and it does not time out when I use the array, or even when I put in large amounts of data (I tested it with an array that has about 20-50 characters per entry and about 500 entries). Just make sure to define the var sheet or put in your own variable.

Try this:
It will allow you to select any column on the sheet.
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
ui.createMenu('Sheet Functions')
.addItem('Get values from column', 'getVals')
.addToUi();
}
function getVals() {
var sheet = ss.getActiveSheet();
var getColumnLetter = ui.prompt('Select column..' , 'Enter the letter of the target column..', ui.ButtonSet.OK_CANCEL);
if(getColumnLetter.getSelectedButton() == ui.Button.CANCEL) {
return } else {
getColumnLetter = getColumnLetter.getResponseText().toUpperCase();
}
var columnNo = getColumnLetter.charCodeAt(0) - 64;
try { var data = sheet.getRange(1, columnNo, sheet.getMaxRows()).getValues().filter(String); } catch (e) { ui.alert('Invalid input please try again.', ui.ButtonSet.OK); return;}
/*
*
* Do what ever you need to do down here
*
*/
}

Related

Copy active cell to other cells containing string

In Google Sheets I'm trying to create a script that will take the value from the active cell and paste that value to any cell in Column B containing the string "HR". Any ideas?
This isn't too bad; you just have to wrap your head around a few concepts from Apps Script and Javascript to make it efficient. But first let's start with the naive approach!
function firstTry() {
var activeSheet = SpreadsheetApp.getActiveSheet(); // whatever is open
var activeCell = SpreadsheetApp.getCurrentCell(); // this is a single-cell range
var activeCellValue = activeCell.getValue(); // could be a string, number, etc
// Now let's look in column B for stuff to change
for (var i = 1; i <= activeSheet.getLastRow(); i++) {
var cell = activeSheet.getRange("B" + i);
var val = cell.getValue();
var valStr = String(val); // We could have gotten a number
if (valStr.indexOf("HR") != -1) {
cell.setValue(activeCellValue);
}
}
}
This will probably work, but isn't too efficient: each call to getValue() or setValue() takes some time. It'd be better to just get all the values at once, and then paste back a modified Column B when we're satisfied:
function improvement() {
var activeSheet = SpreadsheetApp.getActiveSheet(); // whatever is open
var activeCell = SpreadsheetApp.getCurrentCell(); // this is a single-cell range
var activeCellValue = activeCell.getValue(); // could be a string, number, etc
// Now let's look in column B for stuff to change
var rowsWithData = activeSheet.getLastRow() - 1;
var colBRange = activeSheet.getRange(1, // start on row 1
2, // start on column 2
rowsWithData, // this many rows
1); // just one column
// Let's get the data as an array of arrays. JS arrays are 0-based, btw
var colBData = colBRange.getValues();
for (var i = 0; i < colBData.length; i++) {
var val = colBData[i][0]; // row i, first column
var valStr = String(val); // We might have gotten a number
if (valStr.indexOf("HR") != -1) {
colBData[i][0] = activeCellValue; // modify copied data
}
}
// Lastly, write column B back out
colBRange.setValues(colBData);
}
You could go further with a fancy filter function instead of looping over the data explicitly, but that starts to get less clear.
Caveats as the OP points out in comments below, blindly calling setValues like this will pave over any formulas you have. This would have been no big deal, except that this includes hyperlinks. You could get really involved by calling getFormulas in parallel with getValues and then decide whether to call setValue or setFormula depending on the original contents of each cell.

What is the most efficient way to clear row if ALL cells have a value with Apps Script?

I'm trying to come up with a function that will clear contents (not delete row) if all cells in a range have values. The script below isn't functioning as expected, and I would really appreciate any help/advice you all have. It's currently only clearing out a single line, and doesn't appear to be iterating over the whole dataset. My thought was to iterate over the rows, and check each cell individually. If each of the variables has a value, clear that range and go to the next row.
Here's a link to a sample Google Sheet, with data and the script in Script Editor.
function MassRDDChange() {
// Google Sheet Record Details
var ss = SpreadsheetApp.openById('1bcrEZo3IkXiKeyD47C_k2LIRy9N9M6SI2h2MGK1Cj-w');
var dataSheet = ss.getSheetByName('Data Entry');
// Initial Sheet Values
var newLastColumn = dataSheet.getLastColumn();
var newLastRow = dataSheet.getLastRow();
var dataToProcess = dataSheet.getRange(2, 1, newLastRow, newLastColumn).getValues().filter(function(row) {
return row[0]
}).sort();
var dLen = dataToProcess.length;
// Clear intiial sheet
for (var i = 0; i < dLen; ++i) {
var row = 2;
var orderNumber = dataToProcess[i][0].toString();
var rdd = dataToProcess[i][1].toString();
var submittedBy = dataToProcess[i][2].toString();
var submittedOn = dataToProcess[i][3].toString();
if (orderNumber && rdd && submittedBy && submittedOn) {
dataSheet.getRange(row, 1, 1, newLastColumn).clear();
row++;
} else {
row++; // Go to the next row
continue;
}
}
}
Thanks!
Since you don't want to delete the rows, just clear() them, and they're all on the same worksheet tab, this is a great use case for RangeLists, which allow you to apply specific Range methods to non-contiguous Ranges. Currently, the only way to create a RangeList is from a an array of reference notations (i.e. a RangeList is different than an array of Range objects), so the first goal we have is to prefix our JavaScript array of sheet data to inspect with a usable reference string. We could write a function to convert array indices from 0-base integers to A1 notation, but R1C1 referencing is perfectly valid to pass to the RangeList constructor, so we just need to account for header rows and the 0-base vs 1-base indexing difference.
The strategy, then, is to:
Batch-read sheet data into a JavaScript Array
Label each element of the array (i.e. each row) with an R1C1 string that identifies the location where this element came from.
Filter the sheet data array based on the contents of each element
Keep elements where each sub-element (the column values in that row) converts to a boolean (i.e., does not have the same value as an empty cell)
Feed the labels of each of the kept rows to the RangeList constructor
Use RangeList methods on the RangeList
Because this approach uses only 3 Spreadsheet calls (besides the initial setup for a batch read), vs 1 per row to clear, it should be considerably faster.
function clearFullyFilledRows() {
// Helper function that counts the number of populated elements of the input array.
function _countValues(row) {
return row.reduce(function (acc, val) {
var hasValue = !!(val || val === false || val === 0); // Coerce to boolean
return acc + hasValue; // true == 1, false == 0
}, 0);
}
const sheet = SpreadsheetApp.getActiveSheet();
const numHeaderRows = 1,
numRows = sheet.getLastRow() - numHeaderRows;
const startCol = 1,
numCols = sheet.getLastColumn();
// Read all non-header sheet values into a JavaScript array.
const values = sheet.getSheetValues(1 + numHeaderRows, startCol, numRows, numCols);
// From these values, return a new array where each row is the origin
// label and the count of elements in the original row with values.
const labeledCounts = values.map(function(row, index) {
var rNc = "R" + (numHeaderRows + 1 + index) + "C";
return [
rNc + startCol + ":" + rNc + (startCol + numCols - 1),
_countValues(row)
];
});
// Filter out any row that is missing a value.
const toClear = labeledCounts.filter(function (row) { return row[1] === numCols; });
// Create a RangeList from the first index of each row (the R1C1 label):
const rangeList = sheet.getRangeList(toClear.map(function (row) { return row[0]; }));
// Clear them all:
rangeList.clear();
}
Note that because these cleared rows are possibly disjoint, your resulting sheet may be littered with rows having data, and rows not having data. A call to sheet.sort(1) would sort all the non-frozen rows in the sheet, moving the newly-empty rows to the bottom (yes, you can programmatically set frozen rows). Depending how this sheet is referenced elsewhere, that may not be desirable though.
Additional references:
Array#filter
Array#reduce
Array#map
JavaScript Logical Operators
JavaScript Comparison Operators

converting nonadjacent columns to proper/title case in Google Sheets

I found something online and it works for changing text to title case; however, it only works on adjacent columns and I need to apply this to multiple nonadjacent columns. I will paste in the script. If you can give a fix to being able to take care of letting the script run on multiple nonadjacent columns that I specify, that would be great. I found some stuff online that says it can do that, but it is not clear to me.
Here is the script that works:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("A_range");
range.activate();
var values = range.getValues();
if (values.map) {
range.setValues(values.map(function(row) {
return row.map(titleCase);
}));
}
else {
range.setValue(titleCase(values));
}
}
function titleCase(str) {
return str.toString().split(/\b/).map(function(word) {
return word ? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() : '';
}).join('');
}
This was from other people on this concept:
The stuff to make it run on other columns is this:
var range1=sheet.getRange("A1:A19").getValues();
var range2=sheet.getRange("C1:C19").getValues();
var range=[],i=-1;
while ( range1[++i] ) {
range.push( [ range1[i][0], range2[i][0] ] );
}
where range will have content from both columns.
data = sheet.getRange("A1:C19").getValues();
for (i = 0; i < data[0].length; i++) {
// do something with data[0][i]
// do something with data[2][i]
}
I am not sure how to implement these 2 other ideas listed above. If you could be really specific, like actually put something into the first script that lets it run on Col. A and Col. D,for example, it would be much better than generalities, as I am really really new to this and have spent an enormous amount of time trying to learn it/get a handle on it. Thanks!
Because making as few calls as possible to the SpreadsheetApp API is better for speed, i'd prefer to simply take a Range of all the cells between the first and the last column, apply the transformation to selected columns and then write the whole lot back again. The only place to edit then if the columns change is a single pattern array.
var columnPattern = [1,5,6,7] // Equivalent to [A,E,F,G]
The script then runs a simple map over the two-dimensional array representing the sheet.
function transform() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Rows (Could be first row and last row, OP isn't clear.
var startRow = 1, endRow = sheet.getLastRow();
// An array with Column indexes for those you want in Title Case.
var columnPattern = [1,5,6,7];
var firstColumn = parseInt(columnPattern.slice(0,1));
var lastColumn = parseInt(columnPattern.slice(-1));
// The whole range
var range = sheet.getRange(startRow,
firstColumn,
endRow,
lastColumn - firstColumn)
// Apply Title Case to selected columns.
var data = range.getValues().map(function(row, i, rows) {
row = row.map(function(col, j, row) {
if(columnPattern.indexOf(j + firstColumn) >= 0) {
col = titleCase(col);
}
return col;
});
return row;
});
range.setValues(data);
}
The only point I'd perhaps clarify is the line where it identifies the columns to amend.
if(columnPattern.indexOf(j + firstColumn) >= 0) {
This just corrects for the columnPattern array not being the same dimension as your sheet. An alternative would be to have an array that did match the x-dimension with boolean values, but this would be less adaptable to your sheet changing size.
I'd resist putting this in an onEdit() function but it depends on your use case as to how often data changed.

How can I effeciently move a range of values and formulas from one column to another using a google sheets script?

I am trying to move the contents of column D to column A and keep them as formulas or values. The code below works but it takes FOREVER!!
I used this answer to put the values and formulas into an array:
How do I copy a row with both values and formulas to an array?
I used this suggestion to separate them out based on their type:
https://productforums.google.com/forum/#!topic/docs/JtcH-U3qC7s
var ss = SpreadsheetApp.getActiveSheet();
var formulas = ss.getRange("D2:D").getFormulas();
var values = ss.getRange("D2:D").getValues();
var merge = new Array(formulas.length);
for( var i in formulas ) {
merge[i] = new Array(formulas[i].length);
for( var j in formulas[i] )
merge[i][j] = formulas[i][j] !== '' ? formulas[i][j] : values[i][j];
}
for (k=0;k<merge.length;k++){
var rowRange = ss.getRange("A2");
var str = merge[k].toString();
var formulaChecker = str.substring(0,1);
if (formulaChecker == "="){
rowRange.offset(k, 0).setFormula(merge[k]);
}else{
rowRange.offset(k, 0).setValue(merge[k]);
}
}
Because it runs so slowly I feel like I missed something.
Is there a way to make it more efficient and run faster?
Try this:
function copyBoth() {
var sh = SpreadsheetApp.getActiveSheet();
var dataLngth = sh.getLastRow();
var rngCol_D = sh.getRange(2, 4, dataLngth, 1); //Set range for source - Example is column D
var formulas = rngCol_D.getFormulas(); //Get all the forumlas from the source range
var values = rngCol_D.getValues();
var rngCol_A = sh.getRange(2, 1, values.length, 1); //Set range for destination - Example is column A
rngCol_A.setFormulas(formulas);//Write all the formulas to the destination:
//Write all the values, individually to each cell.
var i = 0, thisFormula;
for (i=0;i<dataLngth;i+=1) {
thisFormula = formulas[i][0];
//Logger.log('thisFormula: ' + thisFormula);
//Logger.log('typeof thisFormula: ' + typeof thisFormula);
if (thisFormula === "") {
sh.getRange(i+2, 1).setValue(values[i][0]);//Write the individual value to the single cell
};
};
};
This code is very different from the code you are using. It sets all the formulas first. This eliminates the need to write every single cell. You still need to write values to individual cells that are in between the formulas, and that is done at the end. This example writes all the formulas at once, then the values one by one. But you could do it the opposite way. For example, if there are more values than formulas, it might save a couple of milliseconds.
This strategy also eliminates the need to merge the data, which is probably taking a lot of time.

Find string and get its column

Let's say I have a lot of columns and one of them contains "impressions" string (on row 3). What I need to do is to:
1) Find the cell with "impressions" string
2) Get column number or i.e. "D"
3) Based on what I got paste a formula into i.e. D2 cell which gets AVERAGE from a range D4:D*last*
I couldn't find it anywhere so I have to ask here without any "sample" code, since I have no idea on how to achieve what I want. (3rd one is easy but I need to get that "D" first)
There's no way to search in Google Apps Script. Below is a function that will accomplish the first 2 parts for you (by iterating over every cell in row 3 and looking for "impressions"):
function findColumnNumber() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1'); // insert name of sheet here
var range = sheet.getDataRange(); // get the range representing the whole sheet
var width = range.getWidth();
// search every cell in row 3 from A3 to the last column
for (var i = 1; i <= width; i++) {
var data = range.getCell(3,i)
if (data == "impressions") {
return(i); // return the column number if we find it
}
}
return(-1); // return -1 if it doesn't exist
}
Hopefully this will allow you to accomplish what you need to do!
The indexOf method allows one to search for strings:
function findColumnNumber() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet() //whatever tab the code is run on
var data = sheet.getDataRange().getValues();
var header_row_num = 1; // TODO: change this to whichever row has the headers.
var header = data[header_row_num -1] //Remember JavaScript, like most programming languages starts counting (is indexed) at 0. For the value of header_row_num to work with a zero-index counting language like JavaScript, you need to subtract 1
//define the string you want to search for
var searchString = "impressions";
//find that string in the header and add 1 (since indexes start at zero)
var colNum = header.indexOf(searchString) + 1;
return(colNum);