Writing an array in Google Spreadsheets - javascript

I'm trying to learn javascript, so I decided to code a script in Google Apss Script to list all emails with attachment. Until now, I have this code:
function listaAnexos() {
// var doc = DocumentApp.create('Relatório do Gmail V2');
var plan = SpreadsheetApp.create('Relatorio Gmail');
var conversas = GmailApp.search('has:attachment', 0, 10)
var tamfinal = 0;
if (conversas.length > 0) {
var tam = 0
var emails = GmailApp.getMessagesForThreads(conversas);
var cont = 0;
for (var i = 0 ; i < emails.length; i++) {
for (var j = 0; j < emails[i].length; j++) {
var anexos = emails[i][j].getAttachments();
for (var k = 0; k < anexos.length; k++) {
var tam = tam + anexos[k].getSize();
}
}
var msginicial = conversas[i].getMessages()[0];
if (tam > 0) {
val = [i, msginicial.getSubject(), tam];
planRange = plan.getRange('A1:C1');
planRange.setValue(val);
// doc.getBody().appendParagraph('A conversa "' + msginicial.getSubject() + '" possui ' + tam + 'bytes em anexos.');
}
var tamfinal = tamfinal + tam;
var tam = 0;
}
}
}
listaAnexos();
It works, but with 2 problems:
1) It writes the three val values at A1, B1 and C1. But I want to write i in A1, msginicial.getSubject() in B1 and tam in C1.
2) How can I change the range interactively? Write the first email in A1:C1, the second in A2:C2 ...
I know that are 2 very basic questions, but didn't found on google :(

Problem 1: Make sure you use the right method for the range. You've used Range.setValue() which accepts a value as input, and modifies the content of the range using that one value. You should have used Range.setValues(), which expects an array and modifies a range of the same dimensions as the array. (The array must be a two-dimensional array, even if you're only touching one row.)
val = [[i, msginicial.getSubject(), tam]];
planRange = plan.getRange('A1:C1');
planRange.setValues(val);
Problem 2: (I assume you mean 'programmatically' or 'automatically', not 'interactively'.) You can either use row and column numbers in a loop say, with getRange(row, column, numRows, numColumns), or build the range string using javascript string methods.

Related

How to automate randomizing 46 names to create 46 x 6 unique rows and columns in Google sheet?

I am working with automation in Google sheet. Can you help me?
This problem is for sending surveys to 46 people. Each people needs to rate 5 people from those 46 people.
Requirements:
1. 1 rater, for 5 uniques ratees
2. No duplicate name per row (it should be 6 unique names in a row)
3. No duplicate name per column (it should be 46 unique names per column)
Expected output is for us to create 46x6 random names with no duplicates in row and columns.
-
-
Flow:
If a unique matrix across and below can be created, then it's values can be used as keys to the actual name array.
Create a 2D number array with length = number of rows
Loop through required number of columns and rows
Create a temporary array (tempCol) to store current column data
Fill the array with random numbers
Use indexOf to figure out if any random numbers are already present in the currentrow/ current column, if so, get a new random number.
In random cases, where it's impossible to fill up the temporary column with unique random numbers across and below, delete the temporary column and redo this iteration.
Snippet:
function getRandUniqMatrix(numCols, numRows) {
var maxIter = 1000; //Worst case number of iterations, after which the loop and tempCol resets
var output = Array.apply(null, Array(numRows)).map(function(_, i) {
return [i++]; //[[0],[1],[2],...]
});
var currRandNum;
var getRandom = function() {
currRandNum = Math.floor(Math.random() * numRows);
}; //get random number within numRows
while (numCols--) {//loop through columns
getRandom();
for (
var row = 0, tempCol = [], iter = 0;
row < numRows;
++row, getRandom()
) {//loop through rows
if (//unique condition check
!~output[row].indexOf(currRandNum) &&
!~tempCol.indexOf(currRandNum)
) {
tempCol.push(currRandNum);
} else {
--row;
++iter;
if (iter > maxIter) {//reset loop
iter = 0;
tempCol = [];
row = -1;
}
}
}
output.forEach(function(e, i) {//push tempCol to output
e.push(tempCol[i]);
});
}
return output;
}
console.info(getRandUniqMatrix(6, 46));
var data1d = data.map(function(e){return e[0]});
var finalArr = getRandUniqMatrix(6, 46).map(function(row){return row.map(function(col){return data1d[col]})});
destSheet.getRange(1,1,finalArr.length, finalArr[0].length).setValues(finalArr);
The OP wants to create a review matrix in which the names of the reviewed employees are chosen at random, the reviewer cannot review themselves, and the matrix is completed for 46 employees.
Based on previous code, this version builds an array of employee names for each row, in which the name of the reviewer is not included in the array. Five names are chosen at random and applied to the reviewer. The loop then repeats through each of the 46 employees.
For example, in the first round of reviews, "name01" is omitted from the array of employees from which the "reviewees" are randomly chosen. In the second round, "name01" is included, but "name02" is excluded from the array of employees. And so on, such that in each case, the array of employees used for the random selection of five reviews is always 45 names in length, and excludes the name of the reviewer.
The random selection of names to be rated does not ensure an equal and even distribution of reviews among employees. Though each employee will conduct 5 reviews, some employees are reviewed more than 5 times, some less than 5 times, and (depending on the alignment of the sun, the moon and the stars) it is possible that some may not be selected for review.
function s05648755803(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "Sheet3";
var sheet = ss.getSheetByName(sheetname);
// some variables
var randomcount = 30; // how many random names
var rowstart = 7; // ignore row 1 - the header row
var width = 5; // how many names in each row - 1/rater plus 5/ratee
var thelastrow = sheet.getLastRow();
//Logger.log("DEBUG:last row = "+thelastrow)
// get the employee names
var employeecount = thelastrow-rowstart+1;
//Logger.log("DEBUG: employee count = "+employeecount);//DEBUG
// get the data
var datarange = sheet.getRange(rowstart, 1, thelastrow - rowstart+1);
//Logger.log("DEBUG: range = "+datarange.getA1Notation());//DEBUG
var data = datarange.getValues();
//Logger.log("data length = "+data.length);
//Logger.log(data);
var counter = 0;
var newarray = [];
for (c = 0;c<46;c++){
counter = c;
for (i=0;i<data.length;i++){
if(i!=counter){
newarray.push(data[i]);
}
}
//Logger.log(newarray);
var rowdata = [];
var results = selectRandomElements(newarray, 5);
Logger.log(results)
rowdata.push(results);
var newrange = sheet.getRange(rowstart+c, 3, 1, 5);
newrange.setValues(rowdata);
// clear the arrays for the next loop
var newarray=[];
var rowdata = []
}
}
/*
// selectRandomElements and getRandomInt
// Credit: Vidar S. Ramdal
// https://webapps.stackexchange.com/a/102666/196152
*/
function selectRandomElements(fromValueRows, count) {
var pickedRows = []; // This will hold the selected rows
for (var i = 0; i < count && fromValueRows.length > 0; i++) {
var pickedIndex = getRandomInt(0, fromValueRows.length);
// Pick the element at position pickedIndex, and remove it from fromValueRows. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
var pickedRow = fromValueRows.splice(pickedIndex, 1)[0];
// Add the selected row to our result array
pickedRows.push(pickedRow);
}
return pickedRows;
}
function getRandomInt(min,
max) { // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
Screenshot#1
Screenshot#2
Try this. Satisfies all the three requirements.
HTML/JS:
<html>
<title>Unique Employees</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<table id="survey_table" border="1" width="85%" cellspacing="0">
<thead>
<th>Rater</th>
<th>Ratee1</th>
<th>Ratee2</th>
<th>Ratee3</th>
<th>Ratee4</th>
<th>Ratee5</th>
</thead>
<tbody id="table_body">
</tbody>
</table>
<script type="text/javascript">
function arrayRemove(arr, value) {
return arr.filter(function(ele) {
return ele != value;
});
}
function getRandomInt(rm_row, rm_col) {
var temp_arr = [];
for (var k = 1; k <= 46; k++) {
temp_arr.push(k);
}
for (var k = 0; k < rm_row.length; k++) {
temp_arr = arrayRemove(temp_arr, rm_row[k]);
}
for (var k = 0; k < rm_col.length; k++) {
temp_arr = arrayRemove(temp_arr, rm_col[k]);
}
var rand = temp_arr[Math.floor(Math.random() * temp_arr.length)];
return rand;
}
function exclude_num(row_unq, col_unq) {
var rand_int = getRandomInt(row_unq, col_unq);
if (!row_unq.includes(rand_int) && !col_unq.includes(rand_int)) {
arr_row.push(rand_int);
return rand_int;
} else {
return exclude_num(arr_row, arr_cols);
}
}
for (var i = 1; i <= 46; i++) {
var arr_row = [];
arr_row.push(i);
var table_html = '<tr id="Row' + i + '">';
for (var j = 1; j <= 6; j++)
{
if (j == 1) {
table_html += '<td class="Column' + j + ' cells_unq">' + i + '</td>';
} else {
var arr_cols = []
$('.Column' + j).each(function() {
arr_cols.push(Number($(this).text()));
});
var num = exclude_num(arr_row, arr_cols);
table_html += '<td class="Column' + j + ' cells_unq">' + num + '</td>';
}
}
table_html += '</tr>';
var row_html = $('#table_body').html();
$('#table_body').html(row_html + table_html);
}
$('.cells_unq').each(function() {
temp_text = $(this).text();
$(this).text('Name' + temp_text);
});
</script>
<style type="text/css">
td {
text-align: center;
}
</style>
</html>

Parse out concatenate columns into separate rows

Hi guys im using google app script trying to get the data from google form to transpose from raw data to sorted table. But my code is not working. Im trying to do a custom function. and call for =columnSplit(A1:B2, 2, ",").
This is what i have:
the dates all on column A and Concatenate numbers at number B.
9/10/17 13:30:00 1234,4567,8910
9/11/17 12:34:00 0987,6543,21
what i want to get:
9/10/17 13:30:00 1234
9/10/17 13:30:00 4567
9/10/17 13:30:00 8910
9/11/17 12:34:00 0987
9/11/17 12:34:00 6543
I took my reference from here: How to split and transpose results over 2 columns
function columnSplit(reference, index, delimiter) {
var input = reference;
var output = [];
if (input.constructor !== Array) {
input = [[input]];
}
for (var i = 0; i < input.length; i++) {
var parts = input[i][index - 1].toString().split(delimiter);
for (var j = 0; j < parts.length; j++) {
var copy = input[i].slice(0);
copy[index - 1] = parts[j].trim();
output.push(copy);
}
}
return output
}
This works:
function R2C(a1,idx,dlm){
var vA=a1;
var oA=[];
for(var i=0;i<vA.length;i++){
var tA=vA[i][idx].toString().split(dlm);
var oidx=(idx==1)?0:1;
for(k=0;k<tA.length;k++){
if(idx==0){
oA.push([tA[k],vA[i][1]]);
}else{
oA.push([vA[i][0],tA[k]]);
}
}
}
return oA;
}
These are my spreadsheets which show how to use it:
For this function a1 is a selected range. idx is either 0 or 1. dlm is the delimiter.

Sum cells if they are not bold

I'm confused with my Google Apps script which is purposed to calculate the sum of the cells only if these cells are bold.
Here is the source:
function SumIfNotBold(range, startcol, startrow){
// convert from int to ALPHANUMERIC
// - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
var start_col_id = String.fromCharCode(64 + startcol);
var end_col_id = String.fromCharCode(64 + startcol + range[0].length -1);
var endrow = startrow + range.length - 1
// build the range string, then get the font weights
var range_string = start_col_id + startrow + ":" + end_col_id + endrow
var ss = SpreadsheetApp.getActiveSpreadsheet();
var getWeights = ss.getRange(range_string).getFontWeights();
var x = 0;
var value;
for(var i = 0; i < range.length; i++) {
for(var j = 0; j < range[0].length; j++) {
if(getWeights[i][j].toString() != "bold") {
value = range[i][j];
if (!isNaN(value)){
x += value;
}
}
}
}
return x;
Here is the formula:
=(SumIfNotBold(K2:K100,COLUMN(K2), ROW(K2)))*1
I have three major concerns:
When I set up a trigger to launch this script on any edits I accidentally receive an email from Google Apps stating that
TypeError: Cannot read property "length" from undefined. (line 7, file
"SumIfNotBold")
Thus, how can I fix it? Are there any ways to ignore these automatically delivered notifications?
The formula doesn't calculate the sum of cells if they are on the other list. For example, if I put the formula on B list but the cells are located on A list then this script doesn't work properly in terms of deriving wrong calculations.
When the cell values are updated the formula derivation is not. In this case I'm refreshing the formula itself (i.e., changing "K2:K50" to "K3:K50" and once back) to get an updated derivation.
Please, help me with fixing the issues with this script. Or, if it would be better to use a new one to calculate the sum in non-bold cells then I'll be happy to accept your new solution.
Here is a version of this script that addresses some of the issues you raised. It is invoked simply as =sumifnotbold(A3:C8) or =sumifnotbold(Sheet2!A3:C8) if using another sheet.
As any custom function, it is automatically recalculated if an entry in the range to which it refers is edited.
It is not automatically recalculated if you change the font from bold to normal or back. In this case you can quickly refresh the function by delete-undo on any nonempty cell in the range which it sums. (That is, delete some number, and then undo the deletion.)
Most of the function gets a reference to the passed range by parsing the formula in the active cell. Caveat: this is based on the assumption that the function is used on its own, =sumifnotbold(B2:C4). It will not work within another function like =max(A1, sumifnotbold(B2:C4).
function sumifnotbold(reference) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var formula = SpreadsheetApp.getActiveRange().getFormula();
var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
try {
if (args.length == 1) {
var range = sheet.getRange(args[0]);
}
else {
sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
range = sheet.getRange(args[1]);
}
}
catch(e) {
throw new Error(args.join('!') + ' is not a valid range');
}
// everything above is range extraction from the formula
// actual computation begins now
var weights = range.getFontWeights();
var numbers = range.getValues();
var x = 0;
for (var i = 0; i < numbers.length; i++) {
for (var j = 0; j < numbers[0].length; j++) {
if (weights[i][j] != "bold" && typeof numbers[i][j] == 'number') {
x += numbers[i][j];
}
}
}
return x;
}

How to sum up distinct value using javascript

I want to try and sum up distinct value from a list.. currently i am able to do so if theres only 2 similar record. If theres more than 2 i am not able to do the checking. Following is the javascript code:
function validateData(){
var total = document.frm.size.value;
var msg="";
var tbxA;
var tbxB;
var tbxA2;
var tbxB2;
var tbxC;
var totalValue =0;
var repeatedValue= 0;
var row = 0;
var row2 = 0;
for(var i=0; i<parseInt(total); i++){
tbxA = document.getElementById('tbx_A'+i).value;
tbxB = document.getElementById('tbx_B'+i).value-0;
tbxC = document.getElementById('tbx_C'+i).value;
for(var j=i+1; j<parseInt(total); j++){
tbxA2 = document.getElementById('tbx_A'+j).value;
tbxB2 = document.getElementById('tbx_B'+j).value-0;
if (tbxA==tbxA2) {
totalValue = tbxB + tbxB2;
}
if (totalValue != tbxC) {
repeatedValue= 1;
row = i;
row2 = j;
msg+="*total value does not add up at row " +(row2+1);
break;
}
}
if(repeatedValue== 1){
break;
}
}
return msg;
}
For example A:type of fruit, B: total of each fruit, C: how many bought at a time
total of C should be equal to B. i.e Apple: 3+3+4 = 10. So if the total is not equals to 10 it should prompt me an error.
A B C
Apple 10 3
Orange 10 10
Apple - 3
Apple - 4
My code above will prompt error bt it doesnt go beyond 2nd occurence of Apple.
So yes, how should i go about to ensure it loop through the whole list to sum up all similar values?
Thanks in advance for any possible help!
Try this:
var total = +document.frm.size.value,
data = {};
for(var i=0; i<total; ++i) {
var key = document.getElementById('tbx_A'+i).value;
data[key] = data[key] || {B:0, C:0};
data[key].B += +document.getElementById('tbx_B'+i).value || 0;
data[key].C += +document.getElementById('tbx_C'+i).value || 0;
}
for(var i in data) {
if(data.hasOwnProperty(i) && data[i].B != data[i].C) {
return "total value does not add up";
}
}
return "";
Some comments:
parseInt (and parseFloat) is very slow. + operator before string converts it to a number much faster. But if you really want to make sure the numbers are integers, use Math.floor(), Math.round(), Math.ceil() or the faster but illegible |0.
In case you really want parseInt (e.g. you want to convert '123foobar' into 123), always use a radix. For example: parseInt('123', 10)
Avoid doing calculations at the condition of a loop, because they run at each iteration. Just do the calculation once before the loop and save the result in a variable.

string occurrences in a string

I'm am working on a script to count the number of times a certain string (in this case, coordinates) occur in a string. I currently have the following:
if (game_data.mode == "incomings") {
var table = document.getElementById("incomings_table");
var rows = table.getElementsByTagName("tr");
var headers = rows[0].getElementsByTagName("th");
var allcoord = new Array(rows.length);
for (i = 1; i < rows.length - 1; i++) {
cells = rows[i].getElementsByTagName("td");
var contents = (cells[1].textContent);
contents = contents.split(/\(/);
contents = contents[contents.length - 1].split(/\)/)[0];
allcoord[i - 1] = contents
}}
So now I have my variable allcoords. If I alert this, it looks like this (depending on the number of coordinates there are on the page):
584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519,,
My goal is that, for each coordinate, it saves how many times that coordinate occurs on the page. I can't seem to figure out how to do so though, so any help would be much appreciated.
you can use regular expression like this
"124682895579215".match(/2/g).length;
It will give you the count of expression
So you can pick say first co-ordinate 584 while iterating then you can use the regular expression to check the count
and just additional information
You can use indexOf to check if string present
I would not handle this as strings. Like, the table, is an array of arrays and those strings you're looking for, are in fact coordinates. Soooo... I made a fiddle, but let's look at the code first.
// Let's have a type for the coordinates
function Coords(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
return this;
}
// So that we can extend the type as we need
Coords.prototype.CountMatches = function(arr){
// Counts how many times the given Coordinates occur in the given array
var count = 0;
for(var i = 0; i < arr.length; i++){
if (this.x === arr[i].x && this.y === arr[i].y) count++;
}
return count;
};
// Also, since we decided to handle coordinates
// let's have a method to convert a string to Coords.
String.prototype.ToCoords = function () {
var matches = this.match(/[(]{1}(\d+)[|]{1}(\d+)[)]{1}/);
var nums = [];
for (var i = 1; i < matches.length; i++) {
nums.push(matches[i]);
}
return new Coords(nums[0], nums[1]);
};
// Now that we have our types set, let's have an array to store all the coords
var allCoords = [];
// And some fake data for the 'table'
var rows = [
{ td: '04.shovel (633|455) C46' },
{ td: 'Fruits kata misdragingen (590|519)' },
{ td: 'monster magnet (665|506) C56' },
{ td: 'slayer (660|496) C46' },
{ td: 'Fruits kata misdragingen (590|517)' }
];
// Just like you did, we loop through the 'table'
for (var i = 0; i < rows.length; i++) {
var td = rows[i].td; //<-this would be your td text content
// Once we get the string from first td, we use String.prototype.ToCoords
// to convert it to type Coords
allCoords.push(td.ToCoords());
}
// Now we have all the data set up, so let's have one test coordinate
var testCoords = new Coords(660, 496);
// And we use the Coords.prototype.CountMatches on the allCoords array to get the count
var count = testCoords.CountMatches(allCoords);
// count = 1, since slayer is in there
Use the .indexOf() method and count every time it does not return -1, and on each increment pass the previous index value +1 as the new start parameter.
You can use the split method.
string.split('517,594').length-1 would return 2
(where string is '584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519')

Categories