How to split a javascript array using Google Script - javascript

I'm working on a project that outputs a huge array, and I need to clean it up to send in an email. It seems the simplest approach is the split() function, but I can't seem to make it work.
function splitArray() {
var ss = SpreadsheetApp.getActiveSheet();
var row = ss.getLastRow();
var range = ss.getRange(row, 1, 1, ss.getMaxColumns());
var data = range.getValues();
data.split("\n");
Logger.log(data);}

You need to set the return value of data.split("\n"); to something.
You are splitting the value successfully but not storing that value anywhwere
Try:
data = data.split("\n");
or
Logger.log(data.split("\n"));

Related

Convert data from table to table

I was working in a project which is converting some data to another table by an online API (web service), so the plan is fetching data from the API and converting the prices to another table, I still got the same error again and again which is not convert each row as the way I need.
SCREENSHOT : THE UI TO UNDERSTAND THE USE
CODE :
function Send_Button() {
//activate the spreadsheet
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var cellCurrency = spreadsheet.getRange('E9').getValues();
//fatching the data from the API
var res = UrlFetchApp.fetch("https://api.exchangeratesapi.io/latest?base="+cellCurrency).getContentText();
//parsing data to JSON
var json = JSON.parse(res);
//exporting data in variables
var USD=json['rates']['USD'],
CAD=json['rates']['CAD'],
GBP=json['rates']['GBP'],
EUR=json['rates']['EUR'];
//an array to fetch just 4 currencies
var CRN = [USD,CAD,GBP,EUR];
var cellsPrice = spreadsheet.getRange('E5:E8').getValues();
//targeted cell in the second currencies table
var cellsTraget1 = spreadsheet.getRange('H3:K3');
var cellsTraget2 = spreadsheet.getRange('H4:K4');
var cellsTraget3 = spreadsheet.getRange('H5:K5');
var cellsTraget4 = spreadsheet.getRange('H6:K6');
//converting process
for(var i=0;i<4;i++)
{
cellsTraget1.setValue(cellsPrice[0]*CRN[0]);
cellsTraget2.setValue(cellsPrice[1]*CRN[1]);
cellsTraget3.setValue(cellsPrice[2]*CRN[2]);
cellsTraget4.setValue(cellsPrice[3]*CRN[3]);
}
}
You are iterating but not using the iterator variable i, is that correct? Perhaps writing the code in a more readable way with first getting the rows and then the cell value for each column and then iterating over both row and column would make it more readable and makes you find the issue faster.
Are you absolutely sure that your var cellCurrency is the correct range you want?
From your screenshot it appears the right cell is "E10"... but let's assume you fixed that.
Then you have an issue with your array dimensions, your var cellsPrice is a 2D array (Rows, Columns) even if the range you are getting values from is only one row!.
Another issue, your var cellsTraget* is also a 2D Range, so you can't use setValue()... You could use setValues() but the values array MUST match the range's dimension. And as they currently are, they don't match. Hint: transpose them if you want to use said function.
Apart from that, your for-loop makes no sense at all, since you are not looping anyhow!.
Here is some sample working code:
function sendButton() {
// Activate the spreadsheet
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var baseCurrency = "USD";
// Fetching the data from the API
var res = UrlFetchApp.fetch("https://api.exchangeratesapi.io/latest?base="+baseCurrency).getContentText();
// Parsing data to JSON
var json = JSON.parse(res);
// Exporting data in variables
var USD = [json['rates']['USD'], json['rates']['CAD'], json['rates']['GBP'], json['rates']['EUR']];
// I will do it for one row
var articlePrice = spreadsheet.getRange('E5').getValue();
// Mind the array's dimensions!
var convertedPricesRange = spreadsheet.getRange('I5:L5');
var convertedPriceValues = [[articlePrice*USD[0],articlePrice*USD[1],articlePrice*USD[2],articlePrice*USD[3]]];
// Set converted values
convertedPricesRange.setValues(convertedPriceValues);
}
Further reading:
Sheets Class Range

Missing variable name while trying to send sheet row data to GmailApp; Javascript/Google App script

Still on a learning curve here. I am trying to get data from a google sheet and send the data Gmail app but getting Missing variable name error. This is what I have tried for the last 2 hours and I will appreciate help in structuring the code to work.
function emailTheLastRow(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("AO2:AO"+sheet.getLastRow()).getValues();
var searchString = "1";
for (var i = 0; i<range.length; i++) {
if(range[i][0] == searchString) {
var lastRow = sheet.getRange(2+i,1,1,41).getValues();
var data = {
'email':lastRow[0][1],
'project':lastRow[0][2],
'client':lastRow[0][3],
'sdate':lastRow[0][4],
'edate':lastRow[0][5],
'loe':lastRow[0][7],
};
GmailApp.sendEmail("test#gmail.com", "Project", "A new project has been created with the following details: " + data());
}
}
}
You're trying to concatenate a string with a JSON, which is an object and not a string. Use stringify function [1] to convert the object to a string. Add this line after you declare data variable:
data = JSON.stringify(data);
[1] https://www.w3schools.com/js/js_json_stringify.asp

Get values by specific column name - App Script

I'm trying to get values ​​from a specific column using the method getRange and specifying the name of the column using this example that I saw of the following question ... StackOverflow
When I combine it with my code, I got something like this...
function hola (){
var ss1 = SpreadsheetApp.getActiveSpreadsheet();
var ssh1 = ss1.getSheetByName("Sheet 1");
var lsc = ssh1.getLastColumn();
var data = ssh1.getRange(1,1,1,lsc).getValues();//Get 2D array of all values in row one
data = data[0];
var name = data.indexOf('Names') + 1;//Arrays are zero indexed- add 1
Logger.log(name);
var lastRow = ssh1.getLastRow();
var getRange = ssh1.getRange(name +(lastRow)).getValue();
Logger.log(getRange);
}
I'm not sure I'm wrong, I hope someone can guide me better :D

Append an array in gSheets?

Firstly I am very inexperienced here so apologies if this is obvious.
I have an array of data that updates automatically and I wish to copy this data out so I have an archive of it.
I have managed to find the following script which works for what I want:
function saveInstaPostData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("xxx");
var data0 = sheet.getRange("xxx!A2:AQ21").getValue();
var data1 = sheet.getRange("xxx!B2").getValue();
var data2 = sheet.getRange("xxx!C2").getValue();
var data3 = sheet.getRange("xxx!D2").getValue();
sheet.appendRow([data1,data2,data3,...]);
}
However I have a range of 860 cells, so doing it one by one isn't too feasible.
Reading up on the appendRow method I realise that it (seems) to only be able to append one row at a time. I only have 20 rows so this should still be doable.
I then tried using
function saveInstaPostData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Insta faction post data");
var values = sheet.getSheetValues(2, 1, 1, 43);
sheet.appendRow([values]);
However this outputs the following in the first cell of the new row: [Ljava.lang.Object;#247f2c9a
This seems to be the array I'm trying to append (java: what is this: [Ljava.lang.Object;?) however I can't get it to work!
[I have also tried using
function saveInstaPostData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Insta faction post data");
var range = sheet.getRange(2,1,20,43);
var values = range.getValues();
sheet.appendRow([values]);
This outputs ' Range ' in the first cell of the new row.
]
Any pointers would be really appreciated,
Thanks,
On your example, you try to append a tri dimensionnal array:
var values = sheet.getSheetValues(2, 1, 1, 43);
or
var range = sheet.getRange(2,1,20,43);
var values = range.getValues();
Your "values" variable contains a bi dimensionnal array, that you've put in a mono dimensionnal array:
sheet.appendRow([values]); // [values] put bi dimensionnal array in a mono dimensionnal array
To append your data, you need to append each row of your array, one after a other like :
for(var i=0; i<values.length;i++){
sheet.appendRow(values[i]);
}

cant find .getRange google script

I am trying to create a function that takes a spreadsheet and it contents and duplicate into a new one. This is my function:
function executeIt(){
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1dH5Ehdn2sLd0gPLzdq77ntLUWYwbSwh1nxr1vD7FgQc/edit');
var dataRange = ss.getRange(1, 1, 3, 3);
var myData = dataRange.getValues();
var newSS = SpreadsheetApp.create('Myfile ');
newSS.getActiveSheet().getRange(1, 1, 3, 3);
Logger.log(newSS.getUrl());
}
But when i run it, it says an error code with the getRange();
Help please.
As you will see in the documentation, SpreadsheetApp.openByUrl(...) returns a Spreadsheet. Spreadsheet.getRange(a1Notation) takes a string representing the a1 notation of your range, not the start and end indices of your data.

Categories