How to map specific column using GAS? - javascript

From #soMario's answer to a certain question, getting the data of specific column can be done like this:
The following will get columns b,d,f,g from the range A:G.
const rawData = ss.getRange("A:G").getValues().map(([,b,,d,,f,g]) => [b,d,f,g]);
How can I get the same, but using getRange(2,1,sheet.getLastRow(),7) instead?
Thank you!

when you getValues() of any range, it is stored as one array of many arrays, which looks like this, structurally for the range A1:G3 :
[ [ , , , , , , ], [ , , , , , , ], [ , , , , , , ] ]
when you want a specific "column", say column 4 of that range, in javascript/appscript it means you want the 4th element of each of the arrays in the array. When counting from 0, the 4th element is the 3rd "index".
When using the mapping function, each of the elements of the array being mapped is assigned any variable you want. It is common to use "e". So for your specific case you would want to do this
const rawData = ss.getRange("A:G").map(e=>[ e[1], e[3], e[5], e[6] ]);
1,3,5 and 6 being the "indices" of columns B,D,F and G when starting to count with A as 0.
However, it's likely that you'll want a filter on your data as well to only return rows where there are values in column A. If that guess is correct, you can apply a filter before your map like this:
const rawData = ss.getRange("A:G").filter(e=>e[0]).map(e=>[ e[1], e[3], e[5], e[6] ]);

Related

Generalize multiple forEach to execute on the entire array of values not just selected columns of the array. Google Script, JavaScript

I have a function that takes an array of RegEx(es) and applies them to the selected columns of an array of values, and returns this entire array of values with the columns transformed by the RegEx(es)
used like:
values = processRegEx(values, [0,4,7], RgX);
I want to generalize this so that if the array - colIdx has no entries, it runs on the entire array of values.
values = processRegEx(values, [], RgX);
I tried:
colIdx.length > 0 ? row[idx]=row[idx].replaceAll(...n) : row=row.replaceAll(...n);
but this does not work as no RegEx gets applied. the original array values is returned
How do to do this?
What I have so far:
// Add more as needed:
// [Regex, Replacement]
const RgX = [
[/\bN\./g, 'North'],
[/\bS\./g, 'South'],
[/\bSt\./g, 'Street']
];
function processRegEx(arr, colIdx, replaceTable) {
arr.forEach(function(row){
colIdx.forEach(function(idx){
replaceTable.forEach(function(n){
row[idx]=row[idx].replaceAll(...n)
});
});
});
return arr;
};

How to display array data inside textbox using loop? (One textbox per array data)

Good day! I badly need help for this one, I have an array with many elements/data that is needed to be display in textbox. Each array element/data must be inside the textbox. (The Textbox must be dynamically set up using loop with the array data inside it)
arr = ["1"-"2"-"3"-"4"-"5"]; //my array is from the db, this is example only
conv_arr = arr.split("-")
var myArray = [conv_arr];
var ArrayInText = document.createElement('input');
myArray.forEach(function(conv_arr) {
ArrayInText.value = conv_arr ;
document.body.appendChild(ArrayInText);
It displays the array (pretend this is a textbox [ ])
[ 1, 2, 3, 4, 5 ]
I want a result that looks like this (One textbox per element using loop)
[ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ]
You can see the demo here=> https://jsfiddle.net/4ow6k8j5/1/
After removing unnecessary assignments, you can use below simplest solution;
conv_arr = arr.split("-")
conv_arr.forEach(function(elem) {
var ArrayInText = document.createElement('input');
ArrayInText.value = elem ;
document.body.appendChild(ArrayInText);
});

Select Random Item (shown in pairs) from Array & Remove It, Restart Once Array is Empty

I'm super newbie in coding and I need help to achieve this code.
I'm trying to get a random item (in pairs) from an array and then remove it from this array until user gets to the last item or 60 days have gone from using the service (cookie?)... I have build a script with the help of other questions here in stackoverflow and here is my results so far.
`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];
var yourPics = [
dogpics,
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg' ] //This array has 52 cards but I cutted it for example purposes
];
function get_random_number(array){
return Math.floor(Math.random() * array.length |0);
} // here is where I have tried to modify with other scripts like the one in this page https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty with no success
randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});
var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
</script>`
Thank you for your help!
I don't fully understand what you mean by "remove in pairs", but I'll answer presuming you mean you wish to remove the image ending in 02F.jpg at the same time as removing the image ending in 02B.jpg, and then 03F.jpg at the same time as 03B.jpg.
The solution to this that I will propose is that we will structure your data a bit differently to begin with. That is, if those images, the "B image" and "F image" are linked, we could keep them in the same `javascript object. This would look like:
var yourPics = [
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
},
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
}...]
This would then be an array of objects, rather than strings. We can access the bImage property of an object with just
myObject = yourPics[0]
myObject.bImage
We could delete one of those objects those at random via splice.
myRandomlyRemovedObject = yourPics.splice(myIndexToDeleteFrom, 1) would remove 1 object from yourPics at position of myIndexToDeleteFrom, which you presumably would choose randomly. myRandomlyRemovedObject would be assigned to the one object we removed.
I think this object based approach is safer since you will know for a fact that you will removed both matching strings at the same time.

Remove empty row from array in javascript

I am trying to check and remove any empty row in my table mapped to an array in javascript.
Sample array would be like below.
1 2 3
4 5 6
7 8 9
Now this array is having 4 rows and 3rd one is empty which I want to remove. How to do that. I tried using if(adata[i]) is not null, but that wont work since an indivdual value can be null. i want to check for complete row being null
This short code should match your requirement :
var input = [[1,,3], [11,, ,12], [,,,,,], [37,38,39]];
var result = input.filter(element => element.join("") != "");
console.log(result); // [ [ 1, , 3 ], [ 11, , , 12 ], [ 37, 38, 39 ] ]
Edit : for ES5 you'll write rather
var result = input.filter(function(element) {return element.join("") != ""});

push multidimensional array into json object

I am trying to insert some data in my mongodb database and I require data in some specific format
var location1 = [2,3];
var location2 = [];
location2.push(location1);
location2.push(location1);
var location3 = [];
location3.push(location2);
console.log(location3); //this is the format that i require for insert in mongodb
var couponData = {
location:{"type":"Polygon","coordinates":location3},
UsersTargetted:[],
};
console.log(couponData);
But while running the code i get output as:
{ location: { type: 'Polygon', coordinates: [ [Object] ] },
UsersTargetted: [] }
So, how to make coordinates value as given below:
[ [ [ 2, 3 ], [ 2, 3 ] ] ]
Thanks
Update:
I am not inserting anything in mongodb but creating a json object so that I can insert that object in the mongodb. My requirement is that coordinates field in json object should have value shown above. However, when I insert location3 variable, my console doesn`t show the location3 value, instead it is showing [[object]].
Update2:
Thanks Anand. data is getting stored in mongodb as expected. So no issue, maybe some problem in nodeeclipse.
If you are really worried about it then:
console.log( JSON.stringify( location3 );
And that should clear it up, showing the correct nested format.
Oddly, the syntax is documented as the way to do it here

Categories