Get accurate array of dates from sheet - javascript

I have a Google sheet with thousands of lines, each starting with a date. So:
2019-01-30
2019-01-30
2019-02-19
2019-03-06
2019-03-06
...
I need to get that column into a javascript array and then perform additional functions thereon. I know there is some issue with date indexing such that Google 2019-01-30 translates to javascript 2019-01-29 and a logger on the code confirms this.
How can I get that entire column into the Google Apps Script javascript (using dataSheet.getRange().getValues()) and have that be accurate to what is on the sheet? The only way I know is to individually go through each element of the array and add 1. That feels like a bad way to get around it.
Alternatively, am I better off just leaving it as-is and, when I need to output a date from the javascript to the sheet, add 1 at that point?

Get dates in a flat array
function getColumnOne() {
const startrow=2;
const ss=SpreadsheetApp.getActive();
const sh=ss.getActiveSheet();
const rg=sh.getRange(startrow,1,sh.getLastRow()-startrow+1,1);
var dateA=rg.getValues().map(function(r,i){return r[0];});
return dateA;//returns a flat array
}

Related

Using JavaScript, how can I pull info from a database and order it in a list?

I have a rough idea on how to do this, but it doesn't seem to be working too well.
What I have already achieved is pulling all of the data necessary that needs ordered. What I need is a way to take all of that information and order it from the highest number to the lowest number, and then display that in a single embed - without the use of adding more fields. Ideally it should look something like the image included, except inside an embed. I want to be able to loop this so that it automatically updates the message every X amount of seconds with a message edit.
Each row is ordered from #1 to #20 with #1 having the most Points. This is in the [0123] bit.
The code used to select data from the table is:
const [team, teamd, teame] = await pool.query("SELECT * FROM `performancetracker`.`leaderboard`");
The columns I have use for are TeamName and Points.
I've done something similar with the following code:
Object.keys(check).forEach(function(key) {
var row = check[key];
let name = row.TeamName
embed1.addField(`Team:`, `${name}`, true)
})
However, this adds fields to the embed, which I don't want. I'm not too sure how to go about creating an array or object that I can add to and edit later in the code while maintaining the ability to add it as a field in an embed. I'm not fluent with JavaScript, I'm still learning new things and finding new challenges.
I'm not sure I can help you with the updating part because I don't fully understand the question, but you can do this for displaying the embed how you want:
let data;
Object.keys(check).forEach(() => {
var row = check[key];
let name = row.TeamName
data += `Team: ${name}\n`
})
embed1.addDescription(data)
I haven't tested this code, but it should work.

How to output a text file in google apps script

I am using Google scripts to try and output 2 .txt files by reading in the information from Sheet 1.
I want my files to look like below one for just titles and the other for footnotes:
Therefore the ‘|’ character in the footnote column needs to split onto a new line with the same program name listed as above.
The attached sheet is a basic example, but I need guidance which would also work if the footnote column had multiple ‘|’ characters.
Any help is appreciated.
Solution
Use the split() JS String method to obtain your strings in a single array.
When obtaining the values from a Spreadsheet the Apps Script methods will arrange them in multidimensional Arrays using this fashon: sheet[rows][columns].
In this example I will use the 3rd column, but you can of course adapt this method to whatever column serves you best:
function splitter() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var thirdColumnValues = ss.getDataRange().getValues().flatMap(row => row[2].split('|'));
var text = thirdColumnValues.join("\n"); //Just concatenate the values with the "return" symbol
}
Reference
getValues()
JS String

Automate converting text to rows and columns (Google Sheets)

I'm trying to convert order form data submitted from a Squarespace website from the following format to a table with 4 columns:
Store,Item,Quantity,Details;Store2,Item2,Quantity2,Details2; (etc...)
Commas separate columns while semi-colons separate rows.
All the methods I've tried so far have been successful in splitting the data into the desired form, but the problem occurs when new data is added. When the form is submitted, it creates a new row in the next available empty row. I can't seem to find a way to automate the process without receiving cyclical dependency errors, since each order can have any amount of item entries.
Example spreadsheet:
https://docs.google.com/spreadsheets/d/1ZEWtmMiWO0Us76Z7o7GB7Salw1Rl_-1PhK6GzeOD0GM/edit?usp=sharing
The above example splits the data as desired. I cannot figure out how to make it work with the data added as a new row. I would also like to continue using sheets for its cloud functionality.
Any advice is appreciated, including entirely new ways of processing the data, whether with a script, a different remotely accessible order processing app compatible with Squarespace forms, or natively within Sheets.
You want to achieve the following conversion.
Sample formula:
=ARRAYFORMULA(SPLIT(TRANSPOSE(split(A4,";")),","))
In this formula, the cell "A4" has the input value.
You have already used the formula of =TRANSPOSE(split(A10,";")). In this answer, I used this.
For TRANSPOSE(split(A10,";")), the value is splitted with , using SPLIT and ARRAYFORMULA.
Result:
Sample script:
When you want to use Google Apps Script, you can also use the following script.
function myFunction(value) {
const values = value.split(";");
return values.splice(0, values.length - 1).map(e => e.split(",").map(f => isNaN(f) ? f : Number(f)));
}
In this case, please copy and paste the script to the script editor, and put the custom function of =myFunction(A4) to a cell.
The same result with above formula can be obtained.
References:
SPLIT
ARRAYFORMULA
split()
map()

csv to multi-dimensional array

I'm far from good at javascript. I'm cobbling together a page to analyze a csv file and created a page with results.
So I'm using papaparse.js for csv parsing and the stepFn to process each line, to eliminate records using various selection criteria.
I've also included moment.js to handle dates and times.
so there's 3 pieces of data I want to work with. (I'm simplifying).
[fundraising] team, amount, and date (which I'll store as a unix time integer).
I've been trying to see if outdata[teamname] exists, and if it does, update the amount. And if the amount >= goalamount, then populate date (if it's not already populated).
basically my web page allows them to define selection criteria, a goal, and to choose whether the challenge was [who gets their first]/sort on date, or [who got the most] sort on amount. [where total can actually be a count or
if the team isn't in the outdata array, add it, and place in it the total and a date (which of course I have to check for goal-reaching).
I've tried
var exists = typeof outdata[thisteamname];
if (exists == undefined)
{
outdata.push({ team: thisteamname, total: usevalue, adate: 0 });
}
else
{
var z = outdata[thisteamname]['total'];
//---->>> Cannot read property 'total' of undefined
outdata[thisteamname]['total'] += usevalue;
}
etc .. but i think I'm going about it all wrong. Suggestions? I will also need to sort the outdata array by eithe date or total, and loop through it for a top-ten style list at the end to write html.
all help appreciated, I know my javascript looks rather BASICy.

How to implement query function to use Google spreadsheet as a database?

I'm trying to use a spreadsheet as a database, where each sheet would be a table and the name of a person is used as a primary key (It seems not to be the best solution, but the good spreadsheet interface makes me prefer this solution rather than trying to use ScriptDB.)
And I want to do the following: When you select a name on a sheet and press a button on the menu I added, a function performs a search in another table and a screen and shows all the results of that query in the other table, showing properties records that only that table contains (later I want to add the possibility to generate a text file from a GDocs template).
My questions is:
1) Considering this screen/panel UI has a variable length (because the record number may vary in other tables), what is the best way to create this panel/UI in Google Apps Script? (I don't want to use the Logger.log because I want to add a button to convert the query into a file)
2) In addition to this solution (a search in the resulting 2D array):
function test(){ // to test the find function with an argument, 'any' in this case
var result = findItem('any');
if(result){Logger.log(result.getA1Notation())}else{Logger.log('no luck !')};
}
function findItem(item){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = ss.getDataRange().getValues()
for(var n = 0;n<data.length;++n){
if(data[n].indexOf(item)>-1){ // this is a "strict" find, ie the value must be the entire search item. If you want to do partial match you should compare differently...
return (ss.getRange(n+1,data[n].indexOf(item)+1)); // if found return the range. note the +1 because sheets have 1 index while arrays have 0 index
}
}
return false;// if we come to the end of sheet without result...
}
There is an alternative method to perform queries like this?
THANKS for any help!
Create a UI instance. Then a scrollable panel inside a main panel is the best way of doing this and then using array's to search through the data. I typically create header body and footer panels with the body being scrollable

Categories