Below are my sheet data (Table)and I am trying to get the data using loop however result is not generating in the expected format
I Need data in ["11:00-12:00", "13:00-14:00"] however it's generating in 11:00-12:0013:00-14:00
Expacted result is
var msg = ["11:00-12:00", "13:00-14:00"]
Sheet Data
function showData(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var values = sheet.getDataRange().getValues();
var msg = "";
for(var i = 0; i < values.length; i++) {
if(values[i][0] === "A") {
msg += values[i][1]
}
Logger.log(msg)
}
With the way you are doing this, you are just making one large string. Instead of creating a string variable msg, you should make it an array and add using the .push() method.
msg should be a array and not a string
Use Array#push to push items
function showData(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var values = sheet.getDataRange().getValues();
var msg = [];
for(var i = 0; i < values.length; i++) {
if(values[i][0] === "A") {
msg.push(values[i][1])
}
}
Logger.log(msg)
}
Related
I am trying to write a script in Google sheet that should extract a piece of a string using a regex.For example if I have "test test $1.00 test test" I would like to extract only "1.00"
What I have done so far is:
function myFunction() {
var regExp = new RegExp("\$(.*)\s+");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getDataRange();
var values = range.getValues();
var item_description = 0;
var quantity = 1;
var quantity_flat = [];
var item_flat = [];
for (var j = 0; j < values[quantity].length; j++) {
if (values[quantity][j] == "") {
quantity_flat.push(0);
} else {
quantity_flat.push(values[quantity][j]);
}
}
for (var j = 0; j < values[item_description].length; j++) {
var test = regExp.exec(values[item_description][j]);
item_flat.push(test);
}
}
When I check the type of test, I get that it is an Object and has a value of null.
Not sure where is the error. Ideally, I would like to get back a number so that I can push it in an array.
Thanks!
I am trying to create a program which finds the average of a set of data which someone enters. I have tried using this code:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total + data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
However, when I run it, no matter what I put in, it always prints “0”. Thank you in advance for your help.
The problem is in the line
total + data[i];
This code will be executed at some result will be generated. But then nothing happens to that value. In javascript Numbers are primitive types. Except objects all data types object. You can't mutate them with =(assigning them to a value).
You need to use assignment expression.
total = total + data[i];
Or the short for that will be
total += data[i];
Another problem is that you are not converting the result of prompt() to a Number. Use Unary Plus + to convert string to number.
Below is corrected version of your code.
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = +prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
A cleaner and better version can be achieved using do-while and reduce()
var data = [];
var yesno;
do{
var newdata = +prompt("Enter a piece of data (must be a number)");
yesno = confirm("Would you like to add more data?");
data.push(newdata);
}
while (yesno);
var total = data.reduce((ac,a) => ac + a,0);
var average = total / data.length;
document.write(average);
total + data[i] is an "orphaned expression". Use = or +=.
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = +prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
Try this:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a
number)");
data.push(newdata);
var yesno = confirm("Would you like to add more
data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i ++;
var average = total / data.length;
document.write(average);
}
}
I have a question about a function where I'm trying to get a first look at a multidimensional array.
To explain my problem: In a sheet, I manage my roadmap with projects. A project is composed by 4 rows where I have some information (Project Name, Estimated Team, Timeline ...).
And In my timeline, I need to retrieve the first empty rows in multiple arrays (the first non empty is the startDate).
The problem, I have 4 teams in this multidimensional array, and (for example), the start date can be in the 1st team array for the project A, but the start date can be also in the 3rd team array for the project B.
In my function, I'm trying to get to the start date, but my first step is to check the first array ... (projectRange and after in the code)
So ... I think the best way should be check every rows in the first column, and continue like this to the getLastColumn, right?
So, how can I manage my Loop with this way?
function findLastRow(column) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(roadmapSS);
var startRow = 11;
var startCol = 11;
var dataLength = sheet.getLastRow()-(startRow+2);
var rangeData = sheet.getRange(startRow, 2, sheet.getLastRow(), sheet.getLastColumn());
var dataValues = rangeData.getValues();
var projectsList = rangeData.getValues();
var projectDatas = {};
var projectRange = null;
var projectName = null;
var projectPlan = {};
var realStart = null;
for (var i = 0; i < dataLength; i+=4) {
projectDatas = projectsList[i];
var step = startRow+i;
var realStartRange = startRow+i+1
for (var j = 0; j < 1; j+=4) {
projectName = projectDatas[j];
}
projectRange = ([step, startCol, 4, sheet.getLastColumn()]).toString();
var projectPlan = sheet.getRange(step, startCol, 4, sheet.getLastColumn()).getValues();
for (var k = 0; k < projectPlan.length; ++k) {
realStart = projectPlan[k];
for (var l = 0; l < realStart.length; ++l) {
if (realStart[l] != '') {
break;
}
}
}
//sheet.getRange(realStartRange, 2).setValue(columnToLetter([l]))
console.log(projectName, [l], columnToLetter([l]));
}
}
In fact, i'm trying to get the first column of B in this example (because it's the first non empty occurence :
var projectTimeline = [
['','','A','A','','A'],
['','B','B','','B',''],
['','','','C','C',''],
['','','','','D','D']
]
I found my solution :
I throughed the column first, and then the row. It worked, I founded the column :)
function findFirstDate (timeline) {
for (var col = 0; col < timeline[0].length; col++) {
for (var row = 0; row < 4; row++) {
if (timeline[row][col] != '') {
return [col];
}
}
}
}
I want to set two variables in a for loop in JavaScript.
function onOpen(cf) {
var ss = SpreadsheetApp.getActive();
var startRow = 2; // First row of data to process
var numRows = 4;
var sheet1 = ss.getSheetByName("Sheet1");
//for (var n in ss.getSheets()){ {
for (var ree = startRow, n in ss.getSheets(); ree <= numRows; ree++){ {
var rangeToCheck = sheet1.getRange(ree, 1);// column D in row ree
var accesslist = sheet1.getRange(ree,2);
var namee = rangeToCheck.getValue();
var folder = DriveApp.createFolder(namee);
This doesn't seem to work. Does anyone know any alternatives?
So you just need one variable, because they are proportional:
var sssheets=ss.getSheets();//performance improvement
var ssoffset=0;// i think its -1 in your examples
for(var ree=1;ree<=numRows && ree-ssoffset<sssheets.length; ree++){
var sheet = sssheets[ree-ssofset];
...
}
I want to display duplicates found from the sheet in a Browser.Msg box and send the duplicate strings via email.
Additionally extra column could be written to that row where status "DUPLICATE - YES" would be written. However just to get it via email / in a popup would be enough.
I have tried logging the data. I have tried setting variables.
function checkDuplicates() {
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("DATA!F2:F"); // Set Any Range
// "A:A" is for Column A
// And if you want to check duplicates for whole sheet then try this:
// var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var numRows = data.length;
var numColumns = data[0].length;
var dupes = false;
var okdupes0 = 0;
var nodupes0 = 0;
var totbookings0 = 0;
var formats = [];
var values = [];
for (var i = 0; i < numRows; i++) {
formats[i] = [];
for (var j = 0; j < numColumns; j++) {
formats[i][j] = 'WHITE';
if (data[i][j] != '') {
values.push([data[i][j], i, j]);
}
}
}
var numValues = values.length;
for (var k = 0 ; k < numValues - 1; k++) {
if (formats[values[k][1]][values[k][2]] == 'WHITE') {
for (var l = k + 1; l < numValues; l++) {
if (values[k][0] == values[l][0]) {
formats[values[k][1]][values[k][2]] = 'RED';
formats[values[l][1]][values[l][2]] = 'RED';
var dupes = true;
}
}
var okdupes = okdupes0++;
}
var totbookings = totbookings0++;
}
if (dupes) {
// var okdupes = okdupes -1;
var nodupes = totbookings - okdupes;
var emailAddress = "myemail#gmail.com"; // First column
var message = + nodupes + " Duplicate voucher(s) has been found from the system. Duplicate vouchers has been marked with red color."; // Second column
var subject = "System: " + nodupes + " Duplicate Voucher(s) Found!";
MailApp.sendEmail(emailAddress, subject, message);
Browser.msgBox('Warning!', ''+ nodupes +' Possible duplicate voucher(s) has been found and colored red! Please contact the rep who has made the sale. '+ totbookings +' bookings has been scanned through for duplicates.', Browser.Buttons.OK);
} else {
Browser.msgBox('All good!', 'No duplicate vouchers found.', Browser.Buttons.OK);
}
dataRange.setBackgroundColors(formats);
}
You could convert the array of values to a string, then use match to count occurrences.
This code works to find duplicates, even from a two dimensional array. It doesn't determine what cell the duplicate came from. The values of all the duplicates are put into an array.
function findDups() {
var testArray = [['one','two','three'],['three','four','five']];
var allDataAsString = testArray.toString();
Logger.log('allDataAsString: ' + allDataAsString);
//Create one Dimensional array of all values
var allDataInArray = allDataAsString.split(",");
var pattern;
var arrayOfDups = [];
for (var i = 0;i<allDataInArray.length;i++) {
var tempStr = allDataInArray[i];
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var regExp = new RegExp(tempStr, "g");
var count = (allDataAsString.match(regExp) || []).length;
Logger.log('count matches: ' + count);
if (count > 1 && arrayOfDups.indexOf(tempStr) === -1) {
arrayOfDups.push(tempStr);
};
};
Logger.log('arrayOfDups: ' + arrayOfDups);
Browser.msgBox('Thest are the duplicate values: ' + arrayOfDups);
//To Do - Send Email
};
The above example code has a hard coded two dimensional array for testing purposes. There are two occurrences of an element with the value of 'three'.