Can't get .foreach iterator to post multiple lines - arrays

function myFunction() {
/////////////////////////////////////Fill planning/decor package
var managementSheet = SpreadsheetApp.openById("1P3EF4Edu0efzJVV1Sx-0ayAPaAAiRK8Sl0Y1qZHmcf4");
var packageSheet = managementSheet.getSheetByName("Order Contents");
//Order Contents iterater
var c = packageSheet.getMaxColumns();
var n = packageSheet.getLastRow();
var items = packageSheet.getRange(2,1,n,c).getValues();
var filteredItems = items.filter(function(row) {
if(row[2].toString().includes(firstName +" "+lastName))
{
var results =new Array();
var info = new Array();
info[0]=row[3];
info[1]=row[5];
info[2]=row[9];
info[3]=row[14];
info[4]=row[15];
info[5]=row[16];
results[0]= info;
// result = results.every().valueOf();
Logger.log(results)
var row=22
results.forEach(function(value, index) {
Logger.log("The value at index " + index + " is " + value + ".");
generatedInvoice.getRange(22,1,1,7).setValues([[info[0],,info[1],info[2],info[3],info[4],info[5]]])
row= index + 22+1
})}})
}
Hello. First off, I'm new to appscript/javascript/script in general... Secondly, I'm the worst at explaining things and am so over this as I've been working on it for 2 days with only a few food/water/sleep breaks and just can't figure it out.
I'm trying to take rows from one sheet and copy only some of that row's values to a template...
Customer orders are on one sheet.
Order CONTENTS(for all customers' orders) are on another sheet.
I want to generate an invoice containing everything that the customer has ordered. The code I have currently lists only the final row of the "results" array into my template sheet. I want all of the items that the customer ordered to be added to the invoice. I'm trying to figure out how to use "index" to move to the next line and add the next set of values, but I'm not sure what I'm doing wrong. By logging info, I see that everything is being called correctly and adding to the correct spot in the template. The problem is that it only adds the final line of data into the template when I want all of the lines that match a customer's name.

Related

GAS Filter Criteria to Filter records in an Array that have NON-Blank (text) cells in selected single or multiple fields

I'm trying to find a way in Apps Script, using an array method (NOT using a table), to filter records from a large array that have text data in selected fields.
The records in the newly filtered array would contain ONLY those that have any (text) data in the specified field(s).
The filtered data array would then be copied into a 'Sheets' table for further use.
Finding records with blank fields using "" as the criteria, or specific data, such as "Yes", works well.
My work-around involves a 'for' loop to clear records from the table into which the array has been copied. However, this takes more time than than the 'filter' records method.
The example shows the method to filter only records that have a 'Blank' cell in the specified field. I have tried so many possible criteria that I've lost track of every option I have tried, but here are some of the criteria I've tried to find records that have non-blank cells: "<>" !="" !"" "!Null" ">0" "is not null" "!Empty".
var Ss = SpreadsheetApp.getActiveSpreadsheet();
var DataSheet = Ss.getSheetByName("VolunteerListTbl");//Source Table of data
var LstRowNum = DataSheet.getLastRow();
var LstColNum = DataSheet.getLastColumn();
// "DataSheetRangeValues" is an array of entire dataset
var DataSheetRangeValues = DataSheet.getRange(3,1, LstRowNum , LstColNum).getValues();
var FilterCriteria = ""; //CASE: NO Coordinator assigned
var FilteredData = DataSheetRangeValues.filter(function(e){return e[1]===FilterCriteria});
var NewSheetName = "CustomSearch_Tbl"; //Each search gets a different 'Sheet' name
var C_SrchResSheet = Ss.getSheetByName(NewSheetName);
//Copy data from 'FilteredData' array to a new table 'NewSheetName'
C_SrchResSheet.getRange(3,1,FilteredData.length,LstColNum).setValues(FilteredData);
RecordsFound = FilteredData.length;
Try this:
function myfunk() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("VolunteerListTbl");
const lr = sh.getLastRow();
const lc = sh.getLastColumn();
const vs = sh.getRange(3, 1, lr - 2, lc).getValues();//note the numrows param
const fvs = vs.filter(e => e[1] != "");//this does not seem consistent with the description in your question
const nsh = ss.getSheetByName("CustomSearch_Tbl");
nsh.getRange(3, 1, fvs.length, fvs[0].length).setValues(fvs);
}

set value on sidebar

I am having one google sheet having more than 100 rows with column of "NAME, PLACE, PHONE". I want to change /correct the phone number on specific person Ex.John in the side bar (Form.html) and the correct place & phone number to be edit in that specific row of my google sheet "Phonelist". The code.gs given below which is not working. Could you lease rectify the same?
function sidebar() {
var html = HtmlService.createHtmlOutputFromFile("Form").setTitle('Phone Details');
SpreadsheetApp.getUi().sidebar(html);
}
function result(form) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Phonelist");
var data = ws.getDataRange().getValues();
var name = form.name;
var place = form.place;
var phone = form.phone;
for (var i = 1; i < data.length; i++) {
if(data[i][1] == "John"){
var result = [name,place,phone];
ws.getRange(dat[i]).setValue(result);
}
}
}
It is difficult to understand what you exactly need. But there are some issues which are visible.
ws.getRange(data[i])is not valid. See docs. You need a row and a column at least, and in your case also the number of columns since your are inserting a range. Currently you only have a column. The solution is `
const startColumn = 1 // start at column A
const numberOfRows = 1 // update one row at a time
const numberOfColumns = result.length // this will be 3
ws.getRange(data[i], startColumn, numberOfRows, result.length)
.setValues(result) // setValues is correct, setValue is incorrect
The second issue is that you said that NAME is in the first column, but your test is testing against the second column. Array start at 0, i.e. the first item is actual accessed by [0]. therefore your test if(data[i][1] == "John") actually checks if the second column PLACE is equal to "John". To fix this, replace the [1] with [0], so:
if(data[i][0] == "John")
The third issue is handled in the first answer. You are using setValue() which is only to be used to set one cell. But since you are setting a number of cells at one time, you should use setValues() instead.

Google Apps Script: how to create an array of values for a given value by reading from a two column list?

I have a set of data in a Google spreadsheet in two columns. One column is a list of article titles and the other is the ID of a hotel that is in that article. Call it list1.
Example data
I would like returned a new list with article titles in one column, and an array of the hotel IDs in that article in the other column. Call it list2.
Example data
There are thousands of lines that this needs to be done for, and so my hope was to use Google Apps Script to help perform this task. My original thinking was to
Create column 1 of list2 which has the unique article titles (no script here, just the G-sheets =unique() formula.
Iterate through the titles in list2, looking for a match in first column of the list1
If there is a match:
retrieve its corresponding value in column 2
push it to an empty array in column two of list2
move onto next row in list1
if no longer a match, loop back to step 2.
I've written the following code. I am currently getting a type error (TypeError: Cannot read property '0' of undefined (line 13, file "Code")), however, I wanted to ask whether this is even a valid approach to the problem?
function getHotelIds() {
var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
var lastRow = outputSheet.getLastRow();
var data = outputSheet.getRange(2,1,lastRow,2).getValues();
var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
var lastActiveRow = workingSheet.getLastRow();
var itemIDS = [];
for (var i=1; i<=data.length; i++) {
var currentArticle = data[i][0];
var lookupArticle = workingSheet[i][0];
if (currentArticle === lookupArticle) {
var tempValue = [workingSheet[i][1]];
itemIDS.push(tempValue);
}
}
}
Use a simple google sheets formula:
You can use a very simple formula to achieve your goal instead of using long and complicated scripts.
Use =unique(list1!A2:A) in cell A2 of list2 sheet to get the unique hotels.
and then use this formula to all the unique hotels by dragging it down in column B.
=JOIN(",",filter(list1!B:B,list1!A:A=A2))
You got the idea right, but the logic needed some tweaking. The "undefined" error is caused by the workingSheet[i][0]. WorkingSheet is a Sheet object, not an array of data. Also, is not necessary to get the data from list2 (output), it is rather the opposite. You have to get the data from the list1 (source) sheet instead, and iterate over it.
I added a new variable, oldHotel, which will be used to compare each line with the current hotel. If it's different, it means we have reached a different Hotel and the data should be written in list2.
function getHotelIds() {
var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
var outLastRow = outputSheet.getLastRow();
var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
var lastActiveRow = workingSheet.getLastRow();
var sourceValues = workingSheet.getRange("A2:B" + lastActiveRow).getValues();
var itemIDS = [];
var oldHotel = sourceValues[0][0]; //first hotel of the list
for (var i = 0; i < sourceValues.length; i++) {
if (sourceValues[i][0] == oldHotel) {
itemIDS.push(sourceValues[i][1]);
/*When we reach the end of the list, the oldHotel variable will never be different. So the next if condition is needed. Otherwise it wouldn't write down the last Hotel.
*/
if (i == sourceValues.length - 1) {
outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
[sourceValues[i][0], itemIDS.toString()]
]);
}
} else {
outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
[sourceValues[i - 1][0], itemIDS.toString()]
]);
oldHotel = sourceValues[i][0]; //new Hotel will be compared
outLastRow = outputSheet.getLastRow(); //lastrow has updated
itemIDS = []; //clears the array to include the next codes
}
}
}
I also converted the itemIDS array to a String each time, so it's written down in a single cell without issues.
Make sure each column of the Sheet is set to "Plain text" from Format > Number > Plain Text
References
getRange
setValues
toString()

Loop through range to find matching string google scripts

I'm trying to loop through the top title row of my spreadsheet to find the index number of a column based on the title name so that if someone inserts a column my code won't break. Here's what I have so far:
var sheet = SpreadsheetApp.getActive().getSheetByName('RawData');
var values = sheet.getRange(1,1,sheet.getMaxRows(),sheet.getMaxColumns()).getValue(); //line that's breaking
range.setNote("inside function");
var i = 1;
while(values[1][i] != name) {
i++;
}return i;
}
The code appears to break on the line where I set 'values,' and I can't figure out how to access the array I created in order to check which one contains the same string as the 'name' parameter. The setNote line is just for testing purposes, you can ignore it.
Thanks in advance.
EDIT
function getColumnByName() {
var name = "Ready For Testing?";
var ss=SpreadsheetApp.getActive().getSheetByName('RawData');
var vA=ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn()).getValues();
var hA=vA.shift();//returns header array vA still contains the data
var idx={};
var index = hA.forEach(function(name,i){idx[name]=i});//idx['header name'] returns index
return index;
}
I set name just for testing purposes, it will be passed as a parameter when I use the actual function
Try
function getColumnByName() {
var name = "Ready For Testing?";
var ss=SpreadsheetApp.getActive().getSheetByName('RawData');
var vA=ss.getDataRange().getValues();
var hA=vA.shift();//returns header array vA still contains the data
var idx= hA.indexOf(name);
if(idx === -1 ) throw new Error('Name ' + name + ' was not found');
return idx + 1; // Returns the name position
}
Instead of
var values = sheet.getRange(1,1,sheet.getMaxRows(),sheet.getMaxColumns()).getValue();
and instead of
var vA=ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn()).getValues();
use
var values = sheet.getDataRange().getValues();
getValue() only returns the value of top-left cell
using sheet.getMaxRows() / sheet.getMaxColumns() returns the sheet last row / column which could cause getting a lot of blank rows / columns.
compared with the second line code (getLastRow() / getLastColumn()) the proposed code line is "cheaper" (one call to the Spreadsheet Service instead of three (1. getRange, 2. getLastRow, 3 getLastColumn Vs. getDataRange) to get the data range and usually is faster too.
Regarding
var index = hA.forEach(function(name,i){idx[name]=i});
forEach returns undefined ref. Array.prototype.forEach
Try this:
function myFunction() {
var ss=SpreadsheetApp.getActive()
var sh=ss.getSheetByName('RawData');
var vA=sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn()).getValues();
var hA=vA.shift();//returns header array vA still contains the data
var idx={};
hA.forEach(function(h,i){idx[h]=i});//idx['header name'] returns index
var end="is near";//set a break point here and run it down to here in the debugger and you can see hA and idx
}
hA is the header name array
idx is an object that returns the index for a given header name
idx is all you need just learn to put these three lines of code in your script in the future and you won't need to use an external function call to get the index.
var hA=vA.shift();//returns header array vA still contains the data
var idx={};
hA.forEach(function(h,i){idx[h]=i});//idx['header name'] returns index
vA still contains all of your data

Comparing multiple values in Google Sheets with App Script for loops

I would like to compare multiple values in a Google Sheet spreadsheet some using for loops in Google App Script. But i would like some advice on the best way to do it.
To explain below...
I have two spreadsheets, A "FOOD" table, and A "FOOD GROUP" table. 
I've written a for loop script that goes through the entire FOOD table.
If the key value of both tables matches, the script will update a column from the FOOD table with a column from the FOOD GROUP table.
The script works without issues. But it can only compare one column between the 2 tables at a time. I would like to modify this script so I can compare multiple columns at once, without having to create a for loop for each specified column.
I pasted my code below. I can also provide images of my spreadsheet if you need it. 
In any case, I'm new to coding, so any constructive feedback or insight to improve my script will be helpful. I'm happy to answer any questions if anything seems unclear.
function FoodGroup_Test() {
var Data = SpreadsheetApp.getActiveSpreadsheet();
var FoodGroupDataSheet = Data.getSheetByName("Food Groups") // "FoodGroup" sheet
var FoodGroupAllValues = FoodGroupDataSheet.getRange(2, 1, FoodGroupDataSheet.getLastRow()-1,FoodGroupDataSheet.getLastColumn()).getValues();
var FoodGroupDataLastRow = FoodGroupDataSheet.getLastRow();
var FoodDataSheet = Data.getSheetByName("Food") // "Food" sheet
var FoodAllValues = FoodDataSheet.getRange(2, 1, FoodDataSheet.getLastRow()-1,FoodDataSheet.getLastColumn()).getValues();
// Object to contain all FoodGroup column values
var Object = {};
for(var FO = FoodGroupAllValues.length-1;FO>=0;FO--) // for each row in the "FoodGroup" sheet...
{
Object[FoodGroupAllValues[FO][15]] = FoodGroupAllValues[FO][11]; // ...store FoodGroup ID Key value
}
for(var F = FoodAllValues.length-1;F>=0;F--) // for each row in the "Food" sheet...
{
var Food_FoodGroupKey = FoodAllValues[F][94]; // Store FoodGroup Key value.
// ...if the Food value dont match, update it with FoodGroup's value
if (Object[Food_FoodGroupKey] != FoodAllValues[F][95])
{
FoodAllValues[F][95] = Object[Food_FoodGroupKey];
}
}
// declare range to place updated values, then set it.
var FoodDestinationRange = FoodDataSheet.getRange(2, 1, FoodAllValues.length, FoodAllValues[0].length);
FoodDestinationRange.setValues(FoodAllValues);
}
FOOD GROUP Table
FOOD table
In order for your code to work as expected, you should do the following changes to your code:
Update your if condition to this one:
Object[Food_FoodGroupKey] != FoodAllValues[F][95] && object2[] != FAllValues[F][86])
In order to avoid the undefined problem use the following line of code:
FoodDataSheet.createTextFinder("undefined").replaceAllWith("");

Resources