I have a multidimensional array created by taking data from a google spreadsheet. I am attempting to seperate out the data based on results in a specific column. For example:
var j = {
["Mine", "House"],
["Your", "House"],
["his", "apt"]
}
Given that we want to seperate by column 2. We should get in theory:
var new = {
[["Mine", "House"] , ["Your", "House"]],
[["his", "apt"]]
}
Two entries being a house, and 1 being an apartment. I am haveing a huge issue with treating each entry as its own obj. Assuming it is even possible. I guess we would access specific parts of each object like so, new[0][1][1]? This obviously shouldnt work like this. Is there another way to seperate the entries in the way I am attempting? As it stands right now, I believe my code is just creating the same number of rows as in the original data.
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.insertSheet("Report");
var data_sheet =spreadsheet.getSheetByName("Data");
var genCounsel_data = data_sheet.getRange(240, 1, 96, 7).getValues(); //get genCounseling data
var report_sheet = spreadsheet.getSheetByName("Report");
//setup key values for columns in report sheet
report_sheet.appendRow(["Student Service", "Unit Student Service Outcome", "Indicators Data Sources", "How indicator was measured", "Benchmark Data", "Assigned to do Assessment", "Email"])
//seperate out by SS outcomes
var genCounselDataByOutcomes = new Array(new Array()); //all responses for each outcome, also parrellel
var outcomes_freq = new Array(); //parrellel arrays
var found = false;
//get services and frequency;
for(var i=0; i<genCounsel_data.length; ++i){
genCounsel_data[i][OUTCOMES_COL].toString().toLowerCase();
for(var j=0; j<genCounselDataByOutcomes.length && !found; ++j){
if(genCounselDataByOutcomes[j][OUTCOMES_COL] == genCounsel_data[i][OUTCOMES_COL]){
genCounselDataByOutcomes[j].push(genCounsel_data[i]); //ADD to row with same outcomes
++outcomes_freq[j]; //update amount of entries in said outcome
found = true;
}
}
if(found == false){
genCounselDataByOutcomes.push(new Array);
genCounselDataByOutcomes[genCounselDataByOutcomes.length-1].push([genCounsel_data[i]]);
outcomes_freq.push(1);
}
else
found = false;
}
for(var i=0; i<outcomes_freq.length;++i)
Logger.log(outcomes_freq[i]);
//for each outcome select a random one and move entire row to sheet;
for(var i=0; i<genCounselDataByOutcomes.length; ++i){
Logger.log(genCounselDataByOutcomes[i]);
}
QUESTION:
How can I seperate my data as multiple objects in a row of an array and be able to access specific components of each entry as shown in my example above? If this is not exactly possible in this way, is there another solution to this issue?
First of all, your j and new (which by the way is not a valid var name) need a key if they are objects or to be used as array, like below:
var j = [
["Mine", "House"],
["Your", "House"],
["his", "apt"]
];
var newVar = [
[["Mine", "House"] , ["Your", "House"]],
[["his", "apt"]]
];
That said and fixed, you can iterate over your array of arrays and use the column you want to use as filter to get the unique values to be used to group the final result.
Here is the final result:
var j = [
["Mine", "House"],
["Your", "House"],
["his", "apt"]
];
var uniqueValues = [];
var indexColumn = 1; //Here you specify the column you want to use to filter/group the elements from j
j.forEach(function(element){
if(!uniqueValues.includes(element[indexColumn])){
uniqueValues.push(element[indexColumn]);
}
});
//Now you use the `uniqueValues` to filter the `j` array and generate the `groupedArrays` array, which is the one you are looking for:
var groupedArrays = [];
uniqueValues.forEach(function(uniqueValue){
groupedArrays.push(j.filter(function(element){
return element[indexColumn] === uniqueValue;
}));
});
console.log(groupedArrays);
I hope this helps you.
Good luck.
Related
I have an array where I send a set of values after an operation on a spreadsheet followed by taking the average.
Now I want to return each row also along with the above data.
I thought of using two-dimensional arrays.
But I have less clarity in implementing this.
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
return sendArray;
Now i want to send the array rowFirst & rowSecond also
for (var i = 0; i < spreadsheetRows.length; i++)
{
//first row of spreadsheet
rowFirst=[]; //data of first row
rowSecond=[]; //data of second row
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
sendArray.push(rowFirst); // stuck here <---
sendArray.push(rowSecond);// stuck here <----
return sendArray;
How to send the array with these two data( ie rowFirst and rowSecond) . Please guide me.
Output Expected
sendArray=[
var1,
var2,
var3,
varn,
rowFirst=[num1, num2, num3,...numn]
rowSeocnd=[num1, num2, num3,...numn]
]
To answer your immediate question, you can push an array into another array by using square brackets in push.
sendArray.push([rowFirst]);
sendArray.push([rowSecond]);
Based on your comment, you may want to use an Object, not an Array (here's a helpful article on the differences). So, think through why you'd want four variables not associated with anything. Can those be grouped or keyed somehow? There are a number of ways to do this and a simple method is to use dot notation to pair a variable or a data set to an object key.
// declare the object and each array
var sendObject = {}
// from your code...
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
var rowFirst = [variable1, variable2, ...]
}
// Create the key in the Object and assign the array
sendObject.rowFirst = rowFirst;
The output would be:
sendObject = {
"rowFirst": [variable1, variable2, ...]
}
I'm having an issue pulling the correct values out of a for loop in Google Sheets.
Here's my code:
Note: this is a snippet from a larger function
function sendEmails() {
var trackOriginSheet = SpreadsheetApp.getActiveSpreadsheet().getName();
var getMirSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Miranda");
//Set a new object to hold conditional data
var holdingData = new Object();
//Create function to get values from origin sheet
var returnedValues = function (trackOriginSheet) {
//Load dynamic variables into an object via returnedValues()
if (trackOriginSheet === getMirSheet) {
var startMirRow = 2; // First row of data to process
var numRowsMir = 506; // Number of rows to process
// Fetch the range of cells A2:Z506
var dataRangeMir = getMirSheet.getRange(startMirRow, 1, numRowsMir, 26);
// Fetch values for each cell in the Range.
var dataMir = dataRangeMir.getValues();
for (var k in dataMir) {
var secondRowMir = dataMir[k];
var intRefDescMir = secondRowMir[3];
var intAdminActionsMir = secondRowMir[4];
//Push returned data to holdingData Object
holdingData.selectedData = secondRowMir;
holdingData.refDesc = intRefDescMir;
holdingData.adminActions = intAdminActionsMir;
}
}
}
Here's a copy of the sheet I'm working on
What I need to have happened here first, is track the origin sheet, then create an object to hold data returned from the returnedValues() function. Later, I'll call the properties of this object into a send email function.
The problem is that I need to be able to pull data from the selected sheet dynamically (the "Miranda" sheet in this case.) In other words, when a user selects the "Yes" option in column I of the Miranda sheet, the first thing this script needs to do is pull the values of the variables at the top of the for loop within the same row that the user selected "Yes." Then, I'm pushing that data to a custom object to be called later.
It's apparent to me, that I'm doing it wrong. There's, at least, something wrong with my loop. What have I done? :)
EDIT:
After reviewing the suggestion by VyTautas, here's my attempt at a working loop:
for (var k = 0; k < dataMir.length; k++) {
var mirColI = dataMir[k][8];
var mirRefDesc = dataMir[k][2];
var mirAdminActions = dataMir[k][3];
var mirDates = dataMir[k][4];
if (mirColI === "Yes") {
var activeRowMir = mirColI.getActiveSelection.getRowIndex();
//Pull selected values from the active row when Yes is selected
var mirRefDescRange = getMirSheet.getRange(activeRowMir, mirRefDesc);
var mirRefDescValues = mirRefDescRange.getValues();
var mirAdminActionsRange = getMirSheet.getRange(activeRowMir, mirAdminActions);
var mirAdminActionsValues = mirAdminActionsRange.getValues();
var mirDatesRange = getMirSheet.getRange(activeRowMir, mirDates);
var mirDatesValues = mirAdminActionsRange.getValues();
var mirHoldingArray = [mirRefDescValues, mirAdminActionsValues, mirDatesValues];
//Push mirHoldingArray values to holdingData
holdingData.refDesc = mirHoldingArray[0];
holdingData.adminActions = mirHoldingArray[1];
holdingData.dates = mirHoldingArray[2];
}
}
Where did all that whitespace go in the actual script editor? :D
You already correctly use .getValues() to pull the entire table into an array. What you need to do now is have a for loop go through dataMir[k][8] and simply fetch the data if dataMir[k][8] === 'Yes'. I also feel that it's not quite necessary to use for (var k in dataMir) as for (var k = 0; k < dataMir.length; k++) is a lot cleaner and you have a for loop that guarantees control (though that's probably more a preference thing).
You can also reduce the number of variables you use by having
holdingData.selectedData = mirData[k]
holdingData.refDesc = mirData[k][2] //I assume you want the 3rd column for this variable, not the 4th
holdingData.adminActions = mirData[k][3] //same as above
remember, that the array starts with 0, so if you mirData[k][0] is column A, mirData[k][1] is column B and so on.
EDIT: what you wrote in your edits seems like doubling down on the code. You already have the data, but you are trying to pull it again and some variables you use should give you an error. I will cut the code from the if, although I don't really see why you need to both get the active sheet and sheet by name. If you know the name will be constant, then just always get the correct sheet by name (or index) thus eliminating the possibility of working with the wrong sheet.
var titleMirRows = 1; // First row of data to process
var numRowsMir = getMirSheet.getLastRow(); // Number of rows to process
// Fetch the range of cells A2:Z506
var dataRangeMir = getMirSheet.getRange(titleMirRows + 1, 1, numRowsMir - titleMirRows, 26); // might need adjusting but now it will only get as many rows as there is data, you can do the same for columns too
// Fetch values for each cell in the Range.
var dataMir = dataRangeMir.getValues();
for (var k = 0; k < dataMir.length; k++) {
if (dataMir[k][7] === 'Yes') { //I assume you meant column i
holdingData.refDesc = dataMir[k] //this will store the entire row
holdingData.adminActions = dataMir[k][3] //this stores column D
holdingData.dates = dataMir[k][4] //stores column E
}
}
Double check if the columns I have added to those variables are what you want. As I understood the object stores the entire row array, the value in column called Administrative Actions and the value in column Dates/Periods if Applicable. If not please adjust accordingly, but as you can see, we minimize the work we do with the sheet itself by simply manipulating the entire data array. Always make as few calls to Google Services as possible.
in my API, i have few things like suppose name of companies and am printing them in sorted form after fetching from api but their crrosponding URL'sarent getting printed corrosponding to the name of companies
i.e, i have sorted the keys in the object and printed them in ascending order but the values of those keys arent printing corrosponding to those keys
the URL's are getting printed in the same sequence as its there in API but the keys, i have sorted them to print in accending order
am not able to print the values corrosponding to their keys from the object
the function is here:
function fetchFromApi() {
var url = '<My API from where am fetching the data>';
var urlResponse = UrlFetchApp.fetch(url);
var urlResult = JSON.parse(urlResponse);
var key = Object.keys(urlResult);
var tempArr = [];
for (var x in urlResult) {
var value = urlResult[x];
value = value.replace(/\\/g, '');
tempArr.push([value])
}
inputSheet.getRange(2,6,tempArr.length,1).setValues(tempArr);
printData();
}
function printData() {
keys.sort();
key = [];
for (var i=0; i<keys.length; i++) {
key[i] = [];
key[i][0] = keys[i];
}
var range = inputSheet.getRange(2, 1, key.length, 1);
range.setValues(key);
}
You could try writing the keys and values to the sheet and then sort using range.sort(col).
In the for loop in fetchFromApi(), after tempArr.push([value]) do key.push([x]). At the end of the loop, write key to column 1 and tempArr to column 6 of inputSheet. Then, you can do
var range = inputSheet.getRange(2, 1, key.length, 6);
range.sort(1);
which sorts everything between columns 1 and 6 in ascending order according to the value of the keys in column 1. See below for the reference on range.sort(sortSpecObj).
https://developers.google.com/apps-script/reference/spreadsheet/range#sortsortspecobj
I'm trying to get the search terms and their values in the rising table here:
http://www.google.com/trends/explore#cat=0-14&date=today%207-d&cmpt=q
I can't work out what html tag/class/path they're in. How can I work it out? I tried looking at the source code but it wasn't much help.
Any help is really appreciated - Thx! Antoine
The following snippet will return an array of arrays (the overarching array contains values for each table in the page). Each array element has an array where each table row is an object, broken down into it's 'term' and 'value'.
var tableValues = [];
var t = document.querySelectorAll(".trends-table-data");
if(t.length>0){
var rows, row, cells, values;
for(var i=0; i<t.length; i++){
values = [];
rows = t[i].getElementsByTagName("tr");
for(var r=0; r<rows.length; r++){
row = rows[r];
if(row.className.indexOf('trends-table-row')===-1) continue;
cells = row.getElementsByTagName("td");
values.push({
term: cells[0].innerText.replace(/^\s+|\s+$/g, ''),
value: cells[1].innerText.replace(/^\s+|\s+$/g, '')
});
}
tableValues[i] = values;
}
console.log(tableValues);
}
Since there are two tables on the page, the output for the page you're referencing is:
tableValues = [[{"term":"friv","value":"100"},{"term":"baby","value":"55"},{"term":"hot","value":"50"},{"term":"girls","value":"45"},{"term":"games","value":"45"},{"term":"juegos","value":"30"},{"term":"العاب","value":"25"},{"term":"love","value":"25"},{"term":"bible","value":"20"},{"term":"india","value":"20"}],[{"term":"sophiya haque","value":"Breakout"},{"term":"temple run 2","value":"+3,200%"},{"term":"крещение","value":"+700%"},{"term":"dear abby","value":"+450%"},{"term":"temple run","value":"+200%"},{"term":"amber heard","value":"+130%"},{"term":"plein champ","value":"+130%"},{"term":"paranormal activity 4","value":"+90%"},{"term":"scientology","value":"+70%"},{"term":"mama","value":"+60%"}]]
I want to return an array when one of the elements matches an item within an array.
Is the below code the fastest way to loop through an array when a value matches in a javascript array of arrays?
Note : Welcome any suggestions to modify the variable relatedVideosArray to make it a different data structure for better performance.
var relatedVideosArray = [
["1047694110001"],
["1047694111001", "1019385098001","1020367665001","1020367662001", "1019385097001", "1020367667001"],
["1040885813001"],
["1019385094001", "1019385096001"],
["952541791001", "952544511001", "952544512001", "952544508001", "952541790001","952580933001", "952580934001", "1051906367001"]
]
function getRelatedVideos(videoClicked){
var tempStoreArray = [];
var getCurrentId = videoClicked;
var relVideoslen = relatedVideosArray.length;
for(var i in relatedVideosArray) {
tempStoreArray = relatedVideosArray[i];
for(var j in tempStoreArray){
if(tempStoreArray[j] == getCurrentId){
return relatedVideosArray[i];
}
}
}
}
Update: I initially thought of making a key of video ids and values as all the related ids, but I want to display the key as well as all the related ids if any of the ids within the value array are clicked. Hope this helps to explain the constraint I have.
Modern day browsers support Array indexOf.
For the people saying the array indexOf is slower, basic tests on speed.
var values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
console.time("for");
for(var i=0;i<1000;i++){
for(var j=0;j<=values.length;j++){
if(values[j]===20) break;
}
}
console.timeEnd("for");
console.time("reverse for");
for(i=0;i<1000;i++){
for(var j=values.length-1;j>=0;j--){
if(values[j]===1) break;
}
}
console.timeEnd("reverse for");
console.time("while");
for(i=0;i<1000;i++){
var j=0;
while (j<values.length){
if(values[j]===20) break;
j++;
}
}
console.timeEnd("while");
console.time("reverse while");
for(i=0;i<1000;i++){
var j=values.length-1;
while (j>=0){
if(values[j]===1) break;
j--;
}
}
console.timeEnd("reverse while");
console.time("indexOf");
for(var i=0;i<1000;i++){
var x = values.indexOf(20);
}
console.timeEnd("indexOf");
console.time("toString reg exp");
for(var i=0;i<1000;i++){
var x = (/(,|^)20(,|$)/).test(values.toString);
}
console.timeEnd("toString reg exp");
Two possible solutions:
var relatedVideosArray = [
["1047694110001"],
["1047694111001", "1019385098001","1020367665001","1020367662001", "1019385097001", "1020367667001"],
["1040885813001"],
["1019385094001", "1019385096001"],
["952541791001", "952544511001", "952544512001", "952544508001", "952541790001","952580933001", "952580934001", "1051906367001"]
]
//var getCurrentId = "1019385098001";
var getCurrentId = "1040885813001";
console.time("indexOf");
var tempStoreArray = [];
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(subArr.indexOf(getCurrentId)!==-1){
tempStoreArray.push(subArr);
}
}
console.timeEnd("indexOf");
console.log(tempStoreArray);
console.time("toString reg exp");
var tempStoreArray = [];
var re = new RegExp("(,|^)" + getCurrentId + "(,|$)");
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(re.test(subArr.toString())){
tempStoreArray.push(subArr);
}
}
console.timeEnd("toString reg exp");
console.log(tempStoreArray);
I believe so if you keep your current structure. Unless you have a way of 'flattening' the array first, so that rather than being nested, there is simply one array with all the values. If this is out of your control or impractical, then you have no other choice than to iterate over every element and its elements.
Otherwise, would you be able to add the values to a map? The current video id would be the key, and the value would be the list of related videos.
If you have control over the data structure then I highly recommend changing it to something more amenable to the type of searches you are performing. First thing that comes to mind is an array of associative arrays. Each of your video arrays would be keyed with the video id ( set the value to anything you want ). That would make your search O(n), where n = the total number of video lists you have.
I'll post some code for this when I get in front of the computer.