How do I setup arrays with google charts add rows - javascript

I am trying to set up a google scatter chart page from these links...
https://developers.google.com/chart/interactive/docs/gallery/scatterchart
and create data table here...
https://developers.google.com/chart/interactive/docs/drawing_charts#chart.draw
Basically I have the basic demo copy working.
Now I am trying to populate the data table with time and date data like this...
add rows like this...
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('number', 'Time');
data.addColumn('number', 'Date');
data.addRows([
// this raw text works
[22,5],[10,24],[9,5],[10,6],[10,7],[7,8]
// but my var - datetime from database not working
//Error: Every row given must be either null or an array.
datetime
]);
If I manually type in this:
[22,5],[10,24],[9,5],[10,6],[10,7],[7,8]
it works.
Now I am trying to query a database - then do a .each loop to get the data...
//Query the database...
// query here..
datetime = "";
$.each(data, function(key, value) {
//note: each row comes in from the database like:
//thedate: "02/17/2018" thetime: "18:00:00"
//then I split to just get basic hour and day
t = value.thetime.split(":")
d = value.thedate.split("/")
//and create as numbers
tnum = parseInt(t[0]);
dnum = parseInt(d[1]);
//and add to the datetime var
datetime += "["+ dnum + ","+ tnum + "],"
// there was more code to eliminate last ","
// then the end result var datetime looks something like:
//[22,5],[10,24],[9,5],[10,6],[10,7],[7,8]
If I manually paste this into the add rows area - it works, however if just paste the datetime var into the same add rows area. the error says:
Error: Every row given must be either null or an array.
Q: I'm sure I am missing something basic, such as the graph needs numbers that may be showing as strings or my array is wrong or something else. Is there something to change to get the graph to accept my datetime var?

looks like you're trying to create an array from a string,
instead, use an actual array, which addRows expects...
datetime = [];
$.each(data, function(key, value) {
t = value.thetime.split(":")
d = value.thedate.split("/")
tnum = parseInt(t[0]);
dnum = parseInt(d[1]);
datetime.push([dnum, tnum]);
});
data.addRows(datetime);

Related

Why is .setValue() in for-loop skipping columns?

I have this web app in Appscript that receives info from a POST request from Siri Shortcuts.
function doPost(e) {
//Get active spreadsheet and input database tab name.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Test02');
if(typeof e !== 'undefined')
//Retrieve data received and make a string.
var data = JSON.stringify(e);
//1st print. Print string on new row.
sheet.getRange(sheet.getLastRow()+1,1).setValue(data);
//Eliminate all special characters coming from Siri Shortcuts POST request.
data = data.replace(new RegExp(["\\\\"], 'g'), "");
data = data.replace(new RegExp('"', 'g'), "");
data = data.replace(new RegExp("{", 'g'), "");
data = data.replace(new RegExp("}", 'g'), "");
data = data.replace(new RegExp(":", 'g'), "");
//Split all info on the left side of the first parameter and on the right side of the second.
data = data.split('Log')[1];
data = data.split("name")[0];
//2nd print. Print clean string on a new row.
sheet.getRange(sheet.getLastRow()+1,1).setValue(data);
//3rd print. Print all array element on row. End goal is to have them start from column A and keep adding 1 column every loop.
//Split string into array.
var dataArray = data.split(",");
var lastRow = sheet.getLastRow()+1;
for(var i = 0; i < dataArray.length; i++) {
//3rd print, first part. This tests the real data.
sheet.getRange(lastRow,1+[i]).setValue(dataArray[i]);
//3rd print, second part. This tests the index number to try and find why row are being skipped.
sheet.getRange(lastRow+1,1+[i]).setValue([i]);
}
//Use Mail app to send mail after completion.
MailApp.sendEmail("abc123#gmail.com","InningLogger - Test", data);
return;
}
Attached is the result I am getting in the spreadsheet.
I have two problems with rows 3 and 7:
Why is the data not starting from column A?
Why is row 7 skipping a ton
of columns (I hid them for the screenshot) to print the last 3
values?
Thanks!
As #Pointy mentioned, the problem lied within the 1+[i] in the for loop. "Because i is a number in your code, say 3, 1+[i] will be the string "13", not a number. Changing this to [i+1] solved the problem completely.

Google Sheets Calendar

I would like some help in pulling certain data from a google form linked to a spreadsheet and set a certain value in the date of a certain employee. For example if he/she marked as Vacation Leave then the letter V will be marked under the Date. I have attached the link to my calendar to give an example, I have tried searching the net and this is my second time posting here.
I started the Code but I am stuck in actually finding the Cell for a certain date and inserting the letter.
https://docs.google.com/spreadsheets/d/1uFTR2_B7T0QBr7fTflByFffmmiszbNj_RaCvLEfYRCA/edit?usp=sharing
function setData(){
//Spreadsheets
var ss = SpreadsheetApp;
var data = ss.getActiveSpreadsheet().getSheetByName("Data");
var calendar = ss.getActiveSpreadsheet().getSheetByName("Calendar");
//Get last row / Individual Cells from Form
var lRow = data.getLastRow();
var lRowData = data.getRange(lRow,1,1,17).getValues();
var approval = data.getRange(lRow,17,1,1).getValue();
var leave = data.getRange(lRow,9,1,1).getValue();
var agentName = data.getRange(lRow, 5,1,1).getValue();
var dateBefore = data.getRange(lRow, 10,1,1).getValue();
var dateAfter = data.getRange(lRow, 11,1,1).getValue();
//Calander Variable Arrays
var allDates = calendar.getRange("LA1:NJ1").getValues();
var allNames = calendar.getRange("A4:A160").getValues();
for(var i = 0; i<allNames.length; i++){
if (approval === "Approved" && allNames[i][0] === agentName){
//Here I need it to insert the dates under the correct name and date with a value of V H S M U T.
};
};
};
You are building a spreadsheet-based Leave Calendar based on information from a form response. Based on your existing Calendar, you are having problems identifying the relevant leave dates, and then filling calendar cells to indicate proposed leave.
The problem is there are no fields in rows 1,2 or 3 of Calendar that have the same date format as the Start Date and End Date fields on Form. As a result, there's no easy way to search for a match of the form data fields.
The solution, in my view, is to change the format of the date fields in rows 2 and 3 and enable a search to be match.
Row 2
the existing format is "d" - day of the month (Numeric)
change the format to match the Form Start/End dates: "d-MMM-yyyy".
the font colour for this field can be used to "hide" these dates, and the column width reduced also.
Row 3
the existing format is "E" - day of the week (Name)
change the format to combine the existing formats of rows #2 and #3 - "E-d"
Aspects of the script
the form data is retrieved as getDisplayValues(). The purpose of this is to get the date as a string to facilitate the search.
Two sets of Calendar data are obtained
1) the dates row (Row#2)
2) the names column (Col #1). The Javascript map method is used to convert names from a 2D array to a 1D array. This creates an array that can be easily searched.
the Javascript indexOf method is used to find the Column match for the start and end dates, and to match the name in the Calendar Column (which yields the Row)
the script loops through the number of days leave to create a temporary array of "V" values.
using the row number and the start and end column numbers, a range can be defined on calendar and then updated from the values in the temporary array.
Presumably your function would be triggered by onFormSubmit(e).
Form data
Calendar - Before
Calendar - After
function so5871726503(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var form = ss.getSheetByName("Form");
var calendar = ss.getSheetByName("Calander");
//get form data
var formdataRange = form.getRange(6,1,1,9);// test data
var formData = formdataRange.getDisplayValues(); // display values to format date as string
//get the employee name, start date and end date
var formName = formData[0][1];
var formSD = formData[0][3];
var formED = formData[0][4];
// Logger.log("DEBUG: name = "+formName+", start date = "+formSD+", end date = "+formED);
//get Calendar variables
var calLR = calendar.getLastRow();
var calLC = calendar.getLastColumn();
var caldateStart = 9;
var calnameStart=4;
// get Calendar dates
var calDateRange = calendar.getRange(2,caldateStart,1,calLC-caldateStart+1);
var calDateValues = calDateRange.getDisplayValues();
// get Calendar names
var calNameRange = calendar.getRange(calnameStart,1,calLR-calnameStart+1);
var calNameValues = calNameRange.getValues();
var calNames = calNameValues.map(function(e){return e[0];});//[[e],[e],[e]]=>[e,e,e]
// there should be some error checking on indexof results = -1 in case there is a mismatch.
// find form start date in calender
var startdateresult = calDateValues[0].indexOf(formSD);
var startdateresultcol = startdateresult+caldateStart;
// Logger.log("DEBUG: start date result = "+startdateresult+", column = "+startdateresultcol);
// find form end date in calender
var enddateresult = calDateValues[0].indexOf(formED);
var enddateresultcol = enddateresult+caldateStart;
// Logger.log("DEBUG: end date result = "+enddateresult+", column = "+enddateresultcol);
// find form name in calender
var nameresult = calNames.indexOf(formName);
var nameresultrow = nameresult+calnameStart;
// Logger.log("DEBUG: name result = "+nameresult+", row = "+nameresultrow)
// calculate number of days leave
var daysleave = enddateresultcol-startdateresultcol+1
// Logger.log("DEBUG: days leave = "+daysleave)
// create array variable to hold leave data
var leave=[];
// loop to create data to fill Calendar
for (i=0;i<daysleave;i++){
leave.push("V");
}
// Logger.log(leave); // DEBUG
// build leave range
var calLeave = calendar.getRange(nameresultrow,startdateresultcol,1,daysleave);
//Logger.log(calLeave.getA1Notation()); //DEBUG
// Update the leave range
calLeave.setValues([leave]);
}

Datetime array to array with dates, get corresponding time afterwards

Specific situation.. I'm having an array filled with datetimes I pull in via an api.
Users should be able to select a date from a datepicker (only showing dates available in the array) and afterwards see the corresponding time.
So what I've done..
The original array is obtained via php, so before starting to populate the datepicker with possible dates I create an extra array with dates only.
Since I maintain the key's it's possible to put these 2 arrays next to eachother.
Array looks as following:
["8-8-2017,07:00", "26-8-2017,07:00"];
So far so good...
After a user picks a date I trigger this to be able to start digging for the time corresponding that date.
Now it's getting messy...
$('#datepick').datepicker().on("input change", function(e) {
$("#uur").text('');
var selecteddate = e.target.value;
var searchArr = datesArray;
var ind = searchArr.indexOf(selecteddate.toString());
var result = datesArray.filter(function(item) {
return typeof item == 'string' && item.indexOf(selecteddate.toString()) > -1;
});
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
var final = afterComma.replace(":", "u");
$("#uur").text("De warming up party gaat van start rond " + final);
});
The result is that this only works on the last element of the array.
Because I'm splitting based on the comma's. Now I know the easiest way to work arround this would be to change the , that's seperating date and time in another symbol but still I'm wondering why this couldn't be easier.
You convert whole array to string every time. You should change following code:
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
To this;
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
Edit:
I also missed the loop above
//for every item in result, afterComma will refer to related minute string
for (var item in result) {
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
// Do rest here
}

Google Spreadsheet + Apps: Get max value of column, it gives me date format

I'm trying to use HTML and JS to write into a Spreadsheet and I found some useful code to do that. I had to add a column to insert an ID for each entry and I did it like this:
var sheet = SpreadsheetApp.openById("myKey").getSheetByName('Richieste');
var column = 1;
var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();
var maxi = Math.max.apply(Math, colArray);
var id = maxi+1;
// set other params
var vals = [id, date, name, surname, serial, eMail, area, text, ans, flag];
var sheetObj = sheet.appendRow(vals);
Now, if I have an empty sheet, it works for the first two entries: the third ID is set such as 02/01/1900 0.00.00 and you can see a screenshot here.
I cannot understand what's going on... do you know something about this?
Thanks a lot for your help!
S.
It is hard to tell from the information you provided, but it looks like your cell format is set to date time, not a number.

Combine a Date & a Time Column in Google Sheets for a createEvent() function [duplicate]

This question already has an answer here:
How to merge date and time as a datetime in Google Apps Spreadsheet script?
(1 answer)
Closed 7 years ago.
I need to combine two columns into one dateTime column that can be reading by a createEvent function for startDate.
Column F is the date (mm-dd-yyyy) & Column G is the time (HH:mm PM/AM). I am currently combine them in Column H with the following code:
function conCat() {
var sheet = SpreadsheetApp.getActiveSheet();
var numberOfRows = sheet.getLastRow().toString();
var range = sheet.getRange(2,1,numberOfRows,12);
var values = range.getValues();
var consultedAlreadyFlag = sheet.getRange(2,10,numberOfRows,12);
var sheetName = sheet.getSheetName();
//show updating message
consultedAlreadyFlag.setFontColor('red');
var numValues = 0;
for (var row = 2; row < values.length.toString(); row++) {
//check to see if name and type are filled out - date is left off because length is "undefined"
if (values[row][3].length > 0) {
currentStatus = values[row][1];
//check if it's been entered before
if (values[row][9] != 'EMAIL_SENT'){
sheet.getRange(row+2,8,1,1).setValue('=F' +(row+2)+ '+G' +(row+2));
}
else{
//sheet.getRange(row+2,10,1,1).setValue('EMAIL_SENT');
}
numValues++;
}
//hide updating message
consultedAlreadyFlag.setFontColor('green');
}
}
This code isn't working because when someone submits the form, and the code combines the columns, I cannot get the format to come out as "mm-dd-yyyy HH:mm:ss" which I feel I need in order for my createEvent function to work.
How can I get it to combine the two columns to get the format I need?
I wouldn't bother trying to combine the two columns. There's no point in adding another column, I don't think. You can use JavaScript methods like setHours():
function fncAddToCalender() {
var theEventDate = //To Do - Get the Date
var startMin = value from sheet cell
theEventDate.setHours(15); //Sets event date to 3pm
theEventDate.setMinutes(startMin);
var cal = CalendarApp.getDefaultCalendar();
var event = cal.createEvent(calndrTitle, theEventDate, endDate, {
description : theDescrptn,
location : theLocation,
guests : guestToInvite,
sendInvites : true
});
};
The format in the spreadsheet is probably set to "date". And getting the values with Apps Script will probably return a value that's already in a date format. If you have the columns formatted as text, you'd need to change the values to a date.

Categories