I've range of data, and I want to loop the range 52 times and after completing one loop it should add 7 with date last used,
Something like this :-
I have demonstrated it 2 times, but I want to do it 52 times or n number of times.
Need help in figuring out how I can do this, either by formula or script!
Wrote a script for this, it should repeat the range n number of times with dates incrementing by 7 days. Please take a look at the nested for loop for the manipulation of the 2D array.
function dateFill() {
var sheet = SpreadsheetApp.getActiveSheet();
// constants
var numOfIteration = 52;
var DAY_IN_MS = 1000*60*60*24;
var nameArray = ['A','B','C','D','E','F'];
var newArray = [];
var startDate = new Date(sheet.getRange("B1").getValue());
for (i = 0; i < numOfIteration; i++) {
var newDate = new Date();
newDate.setTime(startDate.getTime() + 7*i*DAY_IN_MS);
for (j = 0; j < nameArray.length; j++) {
newArray.push([nameArray[j], newDate]);
}
}
var lr = sheet.getLastRow();
var writeRange = sheet.getRange(lr+1,1,nameArray.length * numOfIteration,2);
writeRange.setValues(newArray);
}
Sample:
Related
JavaScript
I need to do this with for loop,
I want to multiply each element from array (2 * 5 * 10 * 12)
Example
var arrNum = [2,5,10,12]
var sum = 0
for(var i = 0; i < arrNum.length; i++) {
sum = arrNum[i] * // I don't know what to do
Any ideas :) ?
I did something like this
var arrNum = [2,5,10,12]
var sum = 0
var temp = 1
for(var i = 0; i < arrNum.length; i++){
temp *=arrNumbers[i]
if(i== arrNumbers.length-1){
sum = temp
}
}
First of all, you will always get result as 0 because
your starting sum condition is 0 then multiplying it by any number in the array will always give you 0.
Here is what you should do -
var sum = 1
for(var i = 0; i < arrNum.length; i++) {
sum = arrNum[i] * sum;
}
Try something like this:
var total = 1;
for (var i = 0; i < arrNum.length; i++) {
total *= arrNum[i];
}
var result = [2,5,10,12].reduce(function(a,b){return a*b;});
I think your question needs more explaining, I suppose you're in JS environment.
Notice the advanced funtions of ES6; I suggest to get in deep of all these advanced operations.
Please notice that under the hood the operation will be exact a for-loop, but the reduce hides the complexity and leave everything cleaner.
put the first element of the array in sum
then multiply sum * array of i which start at 1 since we put first element in sum and then put the result back in the sum
var arrNum = [2,5,10,12]
var sum = arrNum[0]
for(var i = 1; i < arrNum.length; i++) {
sum = sum * arrNum[i];
}
console.log(sum);
I did something like this
var arrNum = [2,5,10,12]
var sum = 0
var temp = 1
for(var i = 0; i < arrNum.length; i++){
temp *=arrNumbers[i]
if(i== arrNumbers.length-1){
sum = temp
}
}
it works, but var sum is not a real 0 ...
I am a beginner of programming.
The code snippet below in my GS project works very well.
var nextRow = Sheet_current.getLastRow() + 1; // Line 1
var str = "1,2,3,4,5,6";
var temp = new Array(); //Line 3
temp = str.split(",");
var target = new Array(); //Line 5
for (var i = 0; i < temp.length; i++) {
target.push([temp[i]]);
}
Sheet_current.getRange(Sheet_current.getLastRow() + 1, 1, target.length, target[0].length).setValues(target); //Line 9
Results in my spreadsheet file when running the above code:
result
I use a string as input, then convert it into a temporary array (Line 3).
I continue to declare a target array, to pass the values of the temporary array to the target array. (Lines 5 to 7)
Finally, I use the target array to dump the values into my spreadsheet (vertically, each word in the target array corresponds to a row in the spreadsheet file) (Line 9).
Can someone help me how to optimize the code that only through just one array.
Sincerely thank.
If you just want to provide result on differents row and starting from the first column, you can use the appendRow() method. Here is a example of use in your case:
function myFunction() {
var Sheet_current = SpreadsheetApp.getActiveSheet();
var nextRow = Sheet_current.getLastRow() + 1; // Line 1
var str = "1,2,3,4,5,6";
var target = new Array(); //Line 3
target = str.split(",");
for (var i = 0; i < target.length; i++) {
Sheet_current.appendRow([target[i]]);
}
}
Or you can just made the modification you want on your first array to keep your structure like :
function myFunction2(){
var Sheet_current = SpreadsheetApp.getActiveSheet();
var nextRow = Sheet_current.getLastRow() + 1;
var str = "1,2,3,4,5,6";
var temp = new Array();
temp = str.split(",");
for (var i = 0; i < temp.length; i++) {
temp[i] = [temp[i]]; // To convert your Array[] on Array[][]
}
Sheet_current.getRange(Sheet_current.getLastRow() + 1, 1, temp.length, temp[0].length).setValues(temp);
}
But I don't recommend this method, since it's okay for little program, but can be tricky for larger one.
The goal of the loop is to fill each cell over 797 rows across 5 columns A, B, C, D and E with a formula whose cell reference increments by 1.
E.g. Column A rows 6 onwards will have formula "=indirect("'Data Repository'!A3++")"
Column B rows 6 onwards will have formula "=indirect("'Data Repository'!B3++")"
What happens when I run the function however is it only fills in column A. I've checked the execution transcript and execution succeeded is logged after the first column has been filled up. I've tried various variations to no avail.
Below is the last variation I've tested:
function indirect(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Fleet - Weekly V3");
var formulaArray = [];
var columns = ["A","B","C","D","E"];
var row = 2;
var text = '=indirect(\"\'Data Repository\'!';
var headerRow = 6;
var column;
for(i = 0; i < 5; i++) {
column = parseInt(i) + 1;
formula = text + columns[i];
for(i = 0; i < 797; i++) {
row += 1;
if (formulaArray.length == 797) {
sheet.getRange(headerRow, column).offset(0, 0, formulaArray.length).setValues(formulaArray);
} else {
formulaArray.push([formula + row + '")']);
}
Logger.log(formulaArray.length);
}
Logger.log(i)
formulaArray = [];
}
}
Here is where you might be making an error - you need to create the variable i (var i = 0 instead of just i = 0) and if you're nesting loops, you need to have different variables increasing (first loop use i, then nest with j, then nest in that with k etc as needed)
for(var i = 0; i < 5; i++) {
column = parseInt(i) + 1;
formula = text + columns[i];
for(var j = 0; j < 797; j++) {
Untested but I believe it should work if you just substitute that in.
Your problem is in your loops. You are using the 'i' variable twice. Change the for loop that you have nested to iterate over the variable 'j' or something other than 'i'.
I'm looking for the fastest way to pick a random object that has a certain condition (from an array).
In the example below I have a multidimensional array, 50 * 50 that contains objects. I want to pick a random object from that array but that object needs to have a size larger than 100.
while (object.size <= 100)
{
attempts++;
object = grid_array[Math.round(Math.random() * 49)][Math.round(Math.random() * 49)];
}
Currently I have tested this and in some instances it takes over 300+ attempts. Is there a more elegant way to do this?
Thanks,
What I would do is first filter the source array to extract only valid candidates, then return a random one (if there are any).
For example:
function getRandomObject(grid_array:Array, minSize:Number):Object {
var filtered:Array = [];
for(var i:int = 0; i < grid_array.length; i++){
var inner:Array = grid_array[i];
for(var ii:int = 0; ii < inner.length; ii++){
var object:Object = inner[ii];
if(object.size >= minSize){
filtered.push(object);
}
}
}
return filtered.length ? filtered[int(Math.random() * filtered.length)] : null;
}
// example:
var object:Object = getRandomObject(grid_array, 100);
if(object){
// do stuff with `object`
}
I asked if you need the indexes because you could do this with RegExps and the JSON Class (Flash Player 11). With this example I stored the indexes of the objects:
Create random multidimensional Array to test the function
//---I stored a variable size and the indexes inside the Object
//---Size variable will be numbers between 0 and 500
var array:Array = [];
var i;
var j;
var size:uint = 50;
var obj:Object;
for(i = 0; i < size; i++){
array[i] = [];
for(j = 0; j < size; j++){
obj = new Object();
obj.size = Math.floor(Math.random() * 500);
obj.files = i;
obj.columns = j;
array[i][j] = obj;
}
}
Method to get random Object with size property bigger than 100
//---I'll use to search the object a JSON string
var str:String = JSON.stringify(array);
//---Function to get the random Object
function getRandom():Object{
//---RegExp to search object with size between 100 and 500
var reg:RegExp = /\{[^\}]*"size":(?:10[1-9]|1[1-9]\d|[2-5]\d\d)[^\}]*\}/g;
//---Get all matches
var matches:Array = str.match(reg);
//---Return a random match converted to object
//---If no match founded the return will be null
return matches ? JSON.parse( matches[Math.floor(Math.random() * matches.length)] ) : null;
}
I am trying to test if a specific element in an array is a range of characters, from a-z lowercase. what am I doing wrong? I am very new to coding (1 month in) and I am probably trying to do stuff thats too hard for me.
var array ["a","b","c"];
var myRegularExpression = /[a-z]/;
if (myRegularExpression.test(array[index])) {
//do stuff
}
To give you a working example as #Tushar mentioned:
var arr = ["a","b","c","123"];
var myRegularExpression = new RegExp("^[a-z]+$");
var matchCount = 0;
for (var index = 0; index < arr.length; index++) {
if (myRegularExpression.test(arr[index])) {
//do stuff
matchCount += 1;
}
}
document.getElementById("result").innerText = matchCount;
Number of elements matching the regex "^[a-z]+$":
<div id="result"></div>