Identify specific row based on Date [duplicate] - javascript

This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
What this code does is to identify the row of the array based on the input (Date) and return the values associated with the input date.
However, this for loop is not working as it does not respect the if condition and always returns the last row of the array.
function viewData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Overall Cashflow"); //Data entry Sheet
var datasheet = ss.getSheetByName("Cashflow Tracker Data"); //Data Sheet
var data = datasheet.getDataRange().getValues();
var date = formSS.getRange("H5").getDisplayValue();
for (var i = 0; i < data.length; i++){
if (data[i][0] == date) {
break;
}
var oldinflow = data[i][1];
var oldoutflow = data[i][2];
}
formSS.getRange("H8").setValue(oldinflow);
formSS.getRange("H11").setValue(oldoutflow);
}

You need to get the valueOf() of the date object instead.
Try this:
function viewData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Overall Cashflow"); //Data entry Sheet
var datasheet = ss.getSheetByName("Cashflow Tracker Data"); //Data Sheet
var data = datasheet.getDataRange().getValues();
var date = formSS.getRange("H5").getValue().valueOf();
for (var i = 0; i < data.length; i++){
if (data[i][0].valueOf() == date) {
break;
}
var oldinflow = data[i][1];
var oldoutflow = data[i][2];
}
formSS.getRange("H8").setValue(oldinflow);
formSS.getRange("H11").setValue(oldoutflow);
}

getValues() might return Date object for cells holding "dates", by the other hand getDisplayValue() will return a string. This might explain why (data[i][0] == date is no working.
To prevent on quick and dirty solution that might be good enough is instead of using getValues(), to use getDisplayValues().

Related

Converting timestamps to dates in Google sheet script

I am writing a code that targets a column with dates and I would like to get the dates and compare it to the current date so that I can get the difference between the two.
I ran into a problem I am having trouble solving. It seems that when I used .getValues in my range, it placed each timestamp in an array then those arrays in another array. Like this: [[(new Date(1539619200000))], [(new Date(1540396800000))], [(new Date(1540828800000))]]
I would like to place all the values in 1 array only so I can start solving how to convert the timestamps in to normal dates. I am also a beginner with this so I am sorry if this seems like an basic question.
function datesincolumn() //collects only the date values in range
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow(); //will identify last row with any data
entered
var range = sheet.getRange('D2:D' + lastRow); //will get range of cells
with data present
var dates = range.getValues();//gets all values in the range
var CurrentDate = new Date();
var timestamps = [];
for (i = 0; i <= dates.length; i++)
{
if (dates[i] >= i)
{
timestamps.push(dates[i]);
}
}
Logger.log(dates);
}
When you use .getValues(), you will always get a 2-dimensional array. The outer array represents the row, and the inner array represents the columns. Since you're only getting one column, you can simply append [0] to your dates[i].
function datesincolumn() { //collects only the date values in range
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow(); //will identify last row with any data entered
var range = sheet.getRange('D2:D' + lastRow); //will get range of cells with data present
var dates = range.getValues();//gets all values in the range
var CurrentDate = new Date();
var timestamps = [];
for (var i = 0; i <= dates.length; i++) {
var date = dates[i][0];
if (date >= i)
timestamps.push(date);
}
Logger.log(dates);
}

IF Function - Google Scripts - multiple criteria

I'm trying to run an IF function to match the date in the first column to "last month" and the date in the last column to "newest date" and copy and paste all of the rows matching this criteria (excluding the first and last column) to the bottom of the list.
This is the script I'm running and it isn't finding any matches when I know for a fact there are at least 100 rows matching this criteria:
function myFunction() {
var MCS = SpreadsheetApp.openById('[ID REMOVED FOR THIS Q]');
var MRB = MCS.getSheetByName('Media Rates Back');
var MRBrange = MRB.getRange(1,1,MRB.getLastRow(),1).getValues();
var dest = MRBrange.filter(String).length + 1;
var LM = new Date();
LM.setDate(1);
LM.setMonth(LM.getMonth()-1);
var LMs = Date.parse(LM);
var Datenew = MRB.getRange(MRB.getLastRow(),MRB.getLastColumn()).getValue();
var Datecol = MRB.getRange(1,6,MRB.getLastRow(),1).getValues();
var Datenews = Date.parse(Datenew);
for(var i=0; i<MRBrange.length; i++) {
if(Date.parse(MRBrange[i])==LMs && Date.parse(Datecol[i])==Datenews ) {
var NewRange = MRB.getRange(i,2,(MRB.getLastRow()-i),5);
var NewRangeV = NewRange.getValues();
var destination = MRB.getRange(MRB.getLastRow()+1,2);
Logger.log(NewRange);
NewRange.copyTo(destination);
}else{
Logger.log(i);
}
}}
Any help would be appreciated!
Rather than get the columns as separate ranges, I would get the entire range as one array, then loop over that and check the two columns.
I'm also assuming your values are formatted as dates in the Sheet, in which case you don't need to use Date.parse(), and that your actual date logic is correct.
You can try using the debugger and set a breakpoint at the IF, so you can check the values it is comparing. or put a Logger.log call to list your comparisons.
var last_month_column = 1;
var newest_date_column = MRB.getLastColumn();
var MRBrange = MRB.getRange(1,1,MRB.getLastRow(),newest_date_column).getValues();
for(var row in MRBrange) {
if(MRBrange[row][last_month_column]==LMs && Datecol[row][newest_date_column] ==Datenews ) {
/* your copy logic here */
}else{
Logger.log(i);
}
}
I think the problem may be that MRBrange is a 2d Array. So I used another loop to convert it to a 1d array.
function myFunction() {
var MCS = SpreadsheetApp.openById('[ID REMOVED FOR THIS Q]');
var MRB = MCS.getSheetByName('Media Rates Back');
var MRBrangeA = MRB.getRange(1,1,MRB.getLastRow(),1).getValues();//2d array
var MRBrange=[];
for(var i=0;i<MRBrangeA.length;i++)
{
MRBrange.push(MRBrangA[i][0]);//1d array
}
var dest = MRBrange.filter(String).length + 1;
var LM = new Date();//current day
LM.setDate(1);//first day of month
LM.setMonth(LM.getMonth()-1);//first day of last month
var LMs = Date.parse(LM);
var Datenew = MRB.getRange(MRB.getLastRow(),MRB.getLastColumn()).getValue();
var Datecol = MRB.getRange(1,6,MRB.getLastRow(),1).getValues();
var Datenews = Date.parse(Datenew);
for(var i=0; i<MRBrange.length; i++) {
if(Date.parse(MRBrange[i])==LMs && Date.parse(Datecol[i])==Datenews ) {
var NewRange = MRB.getRange(i,2,(MRB.getLastRow()-i),5);
var NewRangeV = NewRange.getValues();
var destination = MRB.getRange(MRB.getLastRow()+1,2);
Logger.log(NewRange);
NewRange.copyTo(destination);
}else{
Logger.log(i);
}
}}

How do I merge duplicate cells together with google app script?

I currently have a list with two columns. The first column is student name, and the second column is the number of points they have.
I imported this list from multiple spreadsheets so there were many duplicates on the names of the students. I am able to remove the duplicates, but I want to keep a tally on the total points they have. For example:
Amy 10
Bob 9
Carol 15
Amy 12
would turn into:
Amy 22
Bob 9
Carol 15
This is what I have so far:
var target = SpreadsheetApp.getActiveSpreadsheet();
var sheet = target.getSheetByName("Sheet2");
var data = sheet.getRange("A2:B1000").getValues();
var newData = new Array();
var k = 0
var finallist = []
for(i in data){
k++;
var row = data[i];
var duplicate = false;
for(j in newData){
if(row[0] == newData[j][0]){
duplicate = true;
var storedHour = sheet.getRange("B"+k).getValue();
var position = finallist.indexOf(row[0]);
var originalCell = sheet.getRange("B"+(position+1));
var originalHour = originalCell.getValue();
originalCell.setValue(originalHour + storedHour);
sheet.getRange(k,2).setValue("")
sheet.getRange(k,1).setValue("")
}
}
if(!duplicate){
newData.push(row);
finallist.push(row[0])
}
}
}
The problem I'm having is that we have a really large data sample and I'm afraid it may run over Google's 5 minute maximum execution time. Is there another more efficient way to achieve my goal?
Your code is running slow because Spreadsheets API methods (like getRange) are time consuming and much slower then other JavaScript code.
Here is optimized function with reduced number of such Spreadsheets API calls:
function calcNumbers()
{
var target = SpreadsheetApp.getActiveSpreadsheet();
var sheet = target.getSheetByName("Sheet2");
var lastRow = sheet.getLastRow();
var dataRange = sheet.getRange(2, 1, lastRow-1, 2);
var data = dataRange.getValues();
var pointsByName = {};
for (var i = 0; i < data.length; i++)
{
var row = data[i];
var curName = row[0];
var curNumber = row[1];
// empty name
if (!curName.trim())
{
continue;
}
// if name found first time, save it to object
if (!pointsByName[curName])
{
pointsByName[curName] = Number(curNumber);
}
// if duplicate, sum numbers
else
{
pointsByName[curName] += curNumber;
}
}
// prepare data for output
var outputData = Object.keys(pointsByName).map(function(name){
return [name, pointsByName[name]];
});
// clear old data
dataRange.clearContent();
// write calculated data
var newDataRange = sheet.getRange(2, 1, outputData.length, 2);
newDataRange.setValues(outputData);
}
Sorting before comparing allows looking at the next item only instead of all items for each iteration. A spillover benefit is finallist result is alphabatized. Execution time reduction significant.
function sumDups() {
var target = SpreadsheetApp.getActiveSpreadsheet();
var sheet = target.getSheetByName("Sheet2");
var data = sheet.getRange("A2:B" + sheet.getLastRow()).getValues().sort();
var finallist = [];
for(var i = 0; i<= data.length - 1; i++){
var hours = data[i][1];
while((i < data.length - 1) && (data[i][0] == data[i+1][0])) {
hours += data[i+1][1];
i++;
};
finallist.push([data[i][0], hours]);
};
Logger.log(finallist);
}
Edit: the simple data structure with the name being in the first column allows this to work. For anything more complex understanding and applying the methods shown in #Kos's answer is preferable

Delete cells in range if less than current date

I have a range of dates in plain text format (must stay this way) and I need to clear them at 1am if the date in each range cell is less than the current date. I can set up the run schedule later, but can anyone tell me why this isn't working?
I'm using =TEXT(TODAY(),"m/dd") to insert the current date in the correct format in cell AE3.
Thank you!
function clearOldDate()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Loads");
var cells = sheet.getRange('AC9:AE33').getValues();
var data = [cells];
var date = sheet.getRange('AE3').getValues();
//var Sdate = Utilities.formatDate(date,'GMT+0900','MM/dd');
for(i=0; i<76; i++)
{
if (date > data[i])
{
data[i].clear();
};
};
};
This should do the trick
function clearOldDate()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("LogSheet");
//getValues gives a 2D array.
var data = sheet.getRange('AC9:AE33').getValues();
var date = sheet.getRange('AE3').getValues();
//var Sdate = Utilities.formatDate(date,'GMT+0900','MM/dd');
//This for loop with loop through each row
for(i=0; i<data.length; i++)
{
//This for loop with loop through each column
for (var j = 0; j < data[i].length ; j ++){
//This assumes Column AC has the dates you are comparing aganist
if (date > data[i][j])
{
//sets that the Row with index i to empty
data[i] = ["","",""]
};
}
};
//finally set the value back into sheet
sheet.getRange('AC9:AE33').setValues(data)
};
Basically, you need to setValues once data array is modified.
Note: This Statement (date > data[i][0]) doesn't work as expected when the values are stored as text.
Edit: Modified the code and added a new for loop to go through each column, based on comments

How to open Google Sheets spreadsheet to cell in a single row that contains today's date

I'm trying to set a Google Sheet document open to the cell in row 2 with the current date using Script Editor. The dates are arranged chronologically, and daily, from A2:IK2. They're formatted mm/dd.
I found one answer on this website for a similar question, however their dates were listed in a single column whereas my dates are in a single row. The following code was posted by Marshmallow here: https://webapps.stackexchange.com/questions/78927/how-to-make-google-sheet-jump-to-todays-row-when-opened).
Marshmallow's answer:
function onOpen() {
var menu = [{name: "Jump to today's date", functionName: "jumpToDate"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("Custom", menu);
jumpToDate();
}
function jumpToDate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("A:A");
var values = range.getValues();
var day = 24*3600*1000;
var today = parseInt((new Date().setHours(0,0,0,0))/day);
var ssdate;
for (var i=0; i<values.length; i++) {
try {
ssdate = values[i][0].getTime()/day;
}
catch(e) {
}
if (ssdate && Math.floor(ssdate) == today) {
sheet.setActiveRange(range.offset(i,0,1,1));
break;
}
}
}
I modified it to:
function onOpen() {
var menu = [{name: "Jump to today's date", functionName: "jumpToDate"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("Custom", menu);
jumpToDate();
}
function jumpToDate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("A2:IK2"); //given that it is in row 2
var values = range.getValues();
var day = 24*3600*1000;
var today = ((new Date().setHours(0,0,0,0))/day);
var ssdate;
for (var i=0; i<values.length; i++) {
try {
ssdate = values[i][0].getTime()/day;
}
catch(e) {
}
if (ssdate && Math.floor(ssdate) == today) {
sheet.setActiveRange(range.offset(0,i,1,1)); //to offset columns not rows
break;
}
}
}
I thought that I had accounted for the transposition from rows to columns (range "A:A" to "A2:IK2" and changing the offset where indicated; however, I am not seeing the code have any effect. Let alone opening to today's date.
What am I missing here? Any suggestions?
Two more places where transposition requires changes are: values[0][i] instead of values[i][0], and values[0].length instead of values.length.
To address RobG's remark, I also changed the comparison logic, replacing division and flooring with straightforward inequalities: the current time must be between the beginning and end of the date stated in the spreadsheet.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("2:2"); // get all 2nd row
var values = range.getValues();
var day = 24*3600*1000;
var now = Date.now();
var ssdate;
for (var i = 0; i < values[0].length; i++) {
try {
ssdate = values[0][i].getTime();
}
catch(e) {
}
if (ssdate && ssdate <= now && now < ssdate + day) {
sheet.setActiveRange(range.offset(0,i,1,1));
break;
}
}
}

Categories