Multiple loops in apps script - javascript

I am trying to run a replace text function on my slides based on an two arrays; the first array is the values that are to be replaced and the second array are the values that the corresponding values in the first array should be replaced with.
I.e. the first value in the first array should be replaced by the first value in the second array.
This is my attempt at doing it
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value2','new value 3'];
for (i = 0, s = 0, x = 0; i < currentPresentationSlide.length, s < array1.length, x < array2.length; i++, s++, x++) {
currentPresentationSlide[i].replaceAllText(array1[s],array2[x])
}
}
What further complicates it is, that the replaceAllText will only run on a single page and not the entire presentation, hence it will have to be run as a loop on each individual page in the slide (which is the reason for the loop with the i variable.
Does anyone know what I am doing wrong, cause this is not working for me

Thanks to Rup in the comments i solved it. Just in case anyone has the same issue this is my solution:
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value 2','new value 3'];
for (i = 0; i < currentPresentationSlide.length; i++) {
for (s = 0; s < array1.length; s++)
currentPresentationSlide[i].replaceAllText(array1[s],array2[s])
}
}

Related

FOR loop and Array issue

I'm using Adobe Livecycle Designer ES4 to create some report. Based on XML a try to fill table. I have problem with Array. I push data into array in for loop. Below examples of my code:
Results - blank textbox
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData["+ i +"]").sfc.value;
sfcArray.push(sfc);
};
this.rawValue = sfcArray.toString();
Results - get all items
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData["+ i +"]").sfc.value;
sfcArray.push(sfc);
this.rawValue = sfcArray.toString();
}
Results - get 2nd item x 10
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData[1]").sfc.value;
sfcArray.push(sfc);
this.rawValue = sfcArray.toString();
}
Why 1st example don't work and 2nd work correct? I need use this array in another loops. How to solve it?
Because, If it has 2 items, and you looping it for 10.
What happends is, when this.rawValue = sfcArray.toString(); is inside the loop, this.rawValue gets updated 2 times. First time One item will be there. second time 2 items.
For the next iteration there is no 3rd item. So code breaks with error. But this.rawValue still have 2 items.
Where as, when this.rawValue = sfcArray.toString(); is outside the loop, the code breaks with error and this.rawValue don't have any items in it.

Looping through array and back to beginning when reaching end

I have a simple array
var answerAttribute = ['A','B','C','D'];
I have 16 list items, what I'm trying to accomplish is loop through the length of the list and regardless of if the list 2 items or 300. I'd lke to have a data attribute associated with it of A,B, C or D.
Here's what I'm working with:
var questionOption = '';
for(var i = 0; i < quizContent.length; i++) {
questionOption = answerAttribute[i % answerAttribute.length];
console.log(questionOption);
}
When logging this to the console, it logs A, AB, ABC, ABCD, ABCDundefined, and keeps repeating undefined until it's reached the loops conclusion. My question is what am I doing incorrectly so that it only logs one letter per loop.
questionOption += answerAttribute[i]
This statement is short-form for questionOption = questionOption + answerAttribute[i]. It will append the next element to questionOption in every iteration of the loop.
It looks like what you want is probably questionOption = answerAttribute[i]. This will replace the value in questionOption with the new element instead of appending it.
You could simply log only the current value, like this:
var questionOption = '';
for (var i = 0; i < quizContent.length; i++) {
//what is questionOption used for?
questionOption += answerAttribute[i];
console.log(answerAttribute[i]);
}
or if you want questionOption to refer to the current value
questionOption = answerAttribute[i];
console.log(questionOption );
You're looping the quizContent indexes and applying them to the answerAttribute array. I believe what you want is a nested loop...
var quizContent = Array(10); // assume you have 10 quiz questions...
var answerAttribute = ['A','B','C','D'];
for (var i = 0; i < quizContent.length; i++) {
// generate a string for each quiz option
var questionOption = '';
for (var n = 0; n < answerAttribute.length; n++) {
questionOption += answerAttribute[n];
}
quizContent[i] = questionOption;
console.log(questionOption);
}
console.log(quizContent);
Somehow I doubt that the question is actually about the logging, and is actually about the resulting string.
Either way, I'd do this without loops.
var answerAttribute = ['A','B','C','D'];
var quizContent = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
var questionOption = answerAttribute
.join("")
.repeat(Math.ceil(quizContent.length / answerAttribute.length))
.slice(0, quizContent.length);
console.log(questionOption);
It just joins the answerAttribute into a string of characters, and repeats that string the number of times that the length of answerAttribute can be divided into quizContent.length (rounded up).
Then the final string is trimmed down to the size of the quizContent to remove any extra content from the rounding up.
Note that this approach assumes a single character per attribute. If not a single, but they're all the same length, it can be adjusted to still work.

Pass array values to another array

I have an array of input fields called '$inputFieldsArray' then I slice them to group by 3 into 'newArray' then I need new array value for each item to assign to another array cause in the end I need an array with input fields values grouped by 3. The end goal is to get an array which contains for 9 input fields ex [[i1,i2,i3],[i4,i5,i6],[i7,i8,i9]].
For some reason 'stringArray' output is nothing, first two arrays print correct results. It's probably some mistake I do regarding JS arrays.. Sorry js is not my main language, I try to learn it. Thanks.
Here is a screenshoot with chrome console:
Here is my function:
$($submitButton).click(function () {
// Get number of input fields
let $total = $("input[name^='bodyHeader']").length;
// Get input fields as objects
let $inputFieldsArray = $("input[name^='bodyHeader']");
let newArray = [];
let stringArray = [];
let j = 0;
// Group input fields by 3
for (let i = 0; i < $total - 1; i += 3) {
newArray[j] = $inputFieldsArray.slice(i, i + 3);
j++;
}
// Extract string values from newArray and pass them into stringArray
for (let k = 0; k < newArray.length - 1; k++) {
stringArray[k][0] = newArray[k][0].value;
stringArray[k][1] = newArray[k][1].value;
stringArray[k][2] = newArray[k][2].value;
}
// Print to test results
console.log($inputFieldsArray);
console.log(newArray);
console.log("String Array: " + stringArray);
... // Function logic is not complete
});
SOLUTION:
There is no way to declare dynamic length bidimensional array in js. Use this approach suggested by #Stephan :
stringArray[k] = [newArray[k][0].value, newArray[k][1].value,
newArray[k[2].value];
or this approach suggested by #Lorenzo Gangi:
var matrix = [],
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
stringArray[k] is undefined because you defined stringArray as [] (Your browser probably threw an exception). Additionally newArray[k] starts at index 0.
You could write stringArray[k] = [newArray[k][0].value, newArray[k][1].value, newArray[k][2].value] instead.
Basically,
stringArray[k]
is undefined yet, therefore setting its [0] property wont work. May do:
stringArray[k] =newArray[k].map(el=>el.value);
Alltogether:
$($submitButton).click(function () {
let stringArray = $("input[name^='bodyHeader']").toArray().reduce((res,_,i,arr)=>((i%3==0 && res.push(arr.slice(i,i+3).map(e=>e.value))),res),[]);
});

JavaScript - Dynamic Array and Looping

Imagine you have a product page. On this page there are two select inputs with options in them.
There is one for Size and Colour. This can change depending on the product, e.g. a curtain might have a size, length and colour (three select menus).
The array is created dynamically (based on each select menu and its options):
var dynamicArr = [],
i,
j,
opt,
$('.select');
for (i = 0; i < select.length; i += 1) {
opt = select.eq(i).find('option');
if (dynamicArr[i] === undefined) {
dynamicArr[i] = [];
}
for (j = 0; j < opt.length; j += 1) {
dynamicArr[i].push(opt.eq(j));
}
}
Imagine the page had a size and colour drop-down. The above would create an array like this:
dynamicArr = [['size'], ['color']]
I want to loop through each of these separately (in order to get individual values and compare them).
My problem starts here. A dynamic array might have a length of 1, 2, 3, 4, 5, 6 (depending on the select options on the page). I therefore can't do this as there won't always be two selects
for (i = 0; i < dynamicArr[0].length; i += 1) {
}
for (i = 0; i < dynamicArr[1].length; i += 1) {
}
How would I go about finding out the length and looping individually like the above e.g. if there are three selects, it will automatically know there are this many and loop through them like above.
If you are still confused, let me know.
Thanks.
You can always use Array.forEach
dynamicArr.forEach(function(el){
console.log(el);
});
I hope I didn't get you wrong, but here's a solution:
for(i = 0; i < dynamicArr.length; i++) {
for(j = 0; j < dynamicArr[i].length; j++) {
// do something here..
}
}
you should try something like this:
dyn.forEach(function(el){//dyn is the dynamic array
console.log(el); //logs to console
});

How to split and add individual values in a string?

In my javascript, I've an array named my_array holding values like 0121, 1201, 0012, 0202 etc.
Each individual digit in the string is of importance. So, in the above example, there are 4 values in one string. E.g. 0121 holds 0,1,2,1.
The values can also be longer too. E.g. 01221, 21021 etc. (This is holding 5 values)
I want to know of the easiest and most effective way to do the following:
Add the first digits of all the strings in the array my_array. E.g. 0+1+0+0 in the above example
Add the second digits (e.g. 1+2+0+2) and so on.
I can loop through the array and split the values, then
for(i=0; i<my_array.length; i++){
var another_array = my_array[i].split();
//Getting too complicated?
}
How can I do it effectively? Someone please guide me.
Something like this
var myArray = ["0121", "1201", "0012", "0202"];
var firstValSum = 0;
for(var i = 0; i < myArray.length; i++) {
var firstVal = myArray[i].split("");
firstValSum += parseInt(firstVal[0], 10);
}
console.log(firstValSum); //1
This could be wrapped into a function which takes parameters to make it dynamic. i.e pass in the array and which part of the string you want to add together.
EDIT - This is a neater way of achieving what you want - this code outputs the computed values in an array as you specified.
var myArray = ["0121", "1201", "0012", "0202"];
var newArr = [];
for(var i = 0; i < myArray.length; i++) {
var vals = myArray[i].split("");
for(var x = 0; x < vals.length; x++) {
var thisVal = parseInt(vals[x], 10);
( newArr[x] !== undefined ) ? newArr[x] = newArr[x] += thisVal : newArr.push(thisVal);
}
}
console.log(newArr); //[1, 5, 3, 6];
Fiddle here
var resultArray = new Array(); // This array will contain the sum.
var lengthEachString = my_array[0].length;
for(j=0; j<lengthEachString ; j++){ // if each element contains 4 elements then loop for 4 times.
for(i=0; i<my_array.length; i++){ // loop through each element and add the respective position digit.
var resultArray[j] = parseInt( my_array[i].charAt(j) ); // charAt function is used to get the nth position digit.
}
}

Categories