String (split and loop ) to Array - javascript

can someone tell me where the below code is missing to get the correct data..
var temprule="MO,WE";
var rulest =[];
var jsondata=[];
rulest=temprule.split(',');
console.log("TTTTT rulest", rulest);
for(var j = 0; j < rulest.length; j++)
{
var day=rulest[j];
entry.day=day;
console.log(entry.day) // log shows MO and WE as per loop
jsondata.push(entry); // but jsondata has 2 entries with day WE
}
incorrect o/p ->[{day=WE},day=WE}] expected--> [{day=MO},day=WE}]

The variable entry needs to be initialized inside the loop.
var temprule="MO,WE";
var rulest =[];
var jsondata=[];
rulest=temprule.split(',');
console.log("TTTTT rulest", rulest);
for(var j = 0; j < rulest.length; j++)
{
var entry={};
var day=rulest[j];
entry.day=day;
console.log(entry.day) // log shows MO and WE as per loop
jsondata.push(entry); // but jsondata has 2 entries with day WE
}
console.log(JSON.stringify(jsondata));
Here is the jsfiddle link with corrected code.
JSFiddle Link

Related

compare column A in google sheets by scripts. when match is correct then paste offset value in both side

I comparing data from Sheet 00 and 01 by loops.
I'm working in VBA and that's my first steps in JavaScripts.
https://docs.google.com/spreadsheets/d/176pTsstzHQ5FfhEvFJswQUidIGMGTi6jjkTavj2BQOQ/edit?usp=sharing
In output i have duplicate data.
Right now, I try to find in logger.log some point to understood
if I understood I need to skip from loop after matching to next iterate.
I am asking for support what I do wrong in guiding me on the right way:)
Thank You in advanced.
compare COL_A - to find - unique - in 2 sheets in a the some workbook.
sheet00 is colected new data to compare with sheet 01.
Problem is: after matching find1,find2 - I have duplicated rows in output.
find_is_value_is_exist_then_paste_in_both_side
function abc() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh_0=ss.getSheetByName("CA_SHEET_00")
var lastRow=sh_0.getLastRow()
var CA_Sheet_00= sh_0.getRange(2,1,lastRow-1,12).getValues();
Logger.log('LastRow 00_CA_SHEET'+' - row - '+lastRow);
var sh_1=ss.getSheetByName("AA_01")
var lastRow_01=sh_1.getLastRow()
var AA_01 = sh_1.getRange(2,1,lastRow_01-1,12).getValues();
Logger.log('lastRow_01 AA_01'+' - row - '+lastRow_01);
var aaa = [];
var bbb = [];
i=0;
j=0;
for (var i = 0; i < CA_Sheet_00.length; i++) {
for (var j = 0; j < AA_01.length; j++) {
if(CA_Sheet_00[i][0]===AA_01[j][0]){
Logger.log('00'+CA_Sheet_00[i][0]+' - CA_SHEET_00 - row '+[i]);
Logger.log('01'+AA_01[j][0]+' - AA_01 - row '+[j]);
aaa.push([CA_Sheet_00[i][11],CA_Sheet_00[3],AA_01[4],]);
bbb.push([CA_Sheet_00[j][3],]);
sh_0.getRange(2+i,13,aaa.length,3).setValues(aaa); // 00
sh_1.getRange(2+j,13,bbb.length,1).setValues(bbb); }} }}
after modification code by Copper it will be defined like that.
I just only separate output in column as single (13,14,15)
function abc() {
var ss=SpreadsheetApp.getActive();
var sh0=ss.getSheetByName("CA_SHEET_00");
var vA=sh0.getRange(2,1,sh0.getLastRow()-1,12).getValues();
var sh1=ss.getSheetByName("AA_01")
var vB=sh1.getRange(2,1,sh1.getLastRow()-1,12).getValues();
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vB.length;j++) {
if(vA[i][0]==vB[j][0]){
sh0.getRange(2+i,13).setValue(Utilities.formatString('%s',vA[i][11]));
sh0.getRange(2+i,14).setValue(Utilities.formatString('%s',vA[i][3]));
sh0.getRange(2+i,15).setValue(Utilities.formatString('%s',vA[i][0]));
sh1.getRange(2+j,13).setValue(vA[i][3]);
}
}
}
}
I don't understand what your question is but I think this is what you're trying to accomplish with your code.
function abc() {
var ss=SpreadsheetApp.getActive();
var sh0=ss.getSheetByName("CA_SHEET_00");
var vA=sh0.getRange(2,1,sh0.getLastRow()-1,12).getValues();
var sh1=ss.getSheetByName("AA_01")
var vB=sh1.getRange(2,1,sh1.getLastRow()-1,12).getValues();
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vB.length;j++) {
if(vA[i][0]==vB[j][0]){
sh0.getRange(2+i,13).setValue(Utilities.formatString('%s,%s,%s',vA[i][11],vA[i][3],vB[i][4]));
sh1.getRange(2+j,13).setValue(vA[i][3]);
}
}
}
}
If I totally missed the point, I apologize;

Transferring data by date from email

I'm fairly new to coding in Google Script, and with Javascript. Basically what I'm trying to do is make a script to update data on a table in a spreadsheet. I have the script to import the email as a CSV, but I'm struggling with transferring the data from the email to the table by matching up the dates. Essentially what I would like the script to do is emulate a vlookup and paste the values from the emails CSV file to the table.
I made a copy of the file as an example of what I'm trying to do. I'm trying to transfer the yellow section of columns A and B of the Data tab to the matching yellow section columns A and B. And if there is no data for the dates then I would like the empty dates to be 0.
https://docs.google.com/spreadsheets/d/1uK3sCUFvcW6lgk962jgTN-yZox-lF8-Z0wm7Zhh-i8I/edit?usp=sharing
Thanks!
This two functions will accomplish your objectives. createArray(hight, width, filling) is just a workaround to create an array of the exact size of the Destination table. moveDates() is the one that compares the timestamps of the Data table with the ones on Destination; and will write down the values of the row if they match, and a zero if they don't.
This second function will first declare a bunch of variables that will save ranges and values for both sheets. After that, it will read all the dates of both tables. Later, it will run through the Destination table searching for coincidences and saving them on the newData array. Finally, the code will write down the newData. I've tested this code on your spreadsheet and it works perfectly.
function createArray(hight, width, filling) {
var array = [];
for (var i = 0; i < hight; i++) {
array[i] = [];
for (var j = 0; j < width; j++) {
array[i][j] = filling;
}
}
return array;
}
function moveDates() {
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
var destinationSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(
'Destination');
var dataRange = dataSheet.getRange(5, 1, 6, 3);
var destinationRange = destinationSheet.getRange(2, 1, 11, 3);
var newDataRange = destinationSheet.getRange(2, 2, 11, 2)
var data = dataRange.getValues();
var destination = destinationRange.getValues();
var dataDates = [];
var destinationDates = [];
var newData = createArray(11, 2, 0);
for (var i = 0; i < data.length; i++) {
dataDates.push(new Date(data[i][0]));
}
for (var i = 0; i < destination.length; i++) {
destinationDates.push(new Date(destination[i][0]));
}
for (var i = 0; i < destination.length; i++) {
for (var j = 0; j < data.length; j++) {
if (destinationDates[i].getTime() === dataDates[j].getTime()) {
newData[i][0] = data[j][1];
newData[i][1] = data[j][2];
}
}
}
newDataRange.setValues(newData);
}
If you need more information or clarifications I'll be happy to help you.

Skipping a line after an array element is printed

I am trying to print out my array vertically. So once one of the items is listed in the array, include a skipped line before the next element is printed.
My code looks like the following. It is printing out, however it's horizontal and not appealing
request.execute(function(resp) {
for (var x = 0; x < resp.items.length; x++){
var str = resp.items[x].title;
var result = str.link(resp.items[x].alternateLink);
linkPush.push(result);
}
document.getElementById("container9").innerHTML = linkPush;
});
Thanks in advance
Try this
document.getElementById("container9").innerHTML = linkPush.join('<br/>');
Wrap anchors with divs
request.execute(function(resp) {
for (var x = 0; x < resp.items.length; x++){
var str = resp.items[x].title;
var result = str.link(resp.items[x].alternateLink);
linkPush.push('<div>', result, ',</div>');
}
document.getElementById("container9").innerHTML = linkPush.join('');
});

Can't access any arrays after sorting another array

I have encountered a very strange bug:
I derive a new array allSavings[] from another one (tours[]) and sort it in the function calculateAllSavings(). Before I call the function I can access tours[] just fine, but afterwards, I can't anymore. The div tags demo1 and demo2 both exist and are working fine for other outputs.
function euclDist(node1,node2){
if(node1 != node2){
var x = Math.pow(nodes[node2].x - nodes[node1].x,2);
var y = Math.pow(nodes[node2].y - nodes[node1].y,2);
var dist = Math.sqrt(x+y);
return dist;
}
else return 0.0;
}
function tourDist(members){
var tourDist = 0.0;
if (members.length>1){
for (i = 1; i < members.length; i++)
tourDist += euclDist(members[i],members[i-1]);
}
return tourDist;
}
function combineTours(tourA, tourB){
tourA.pop();
tourB.shift();
return tourA.concat(tourB);
}
function calculateSaving(tourA,tourB){
var costSeparate = tourDist(tourA) + tourDist(tourB);
var combTour = combineTours(tourA,tourB);
var costCombined = tourDist(combTour);
return costSeparate - costCombined;
}
function calculateAllSavings(){
var allPossibilities = [];
for(var i = 0; i < tours.length; i++){
for(var j = 0; j < tours.length; j++){
if(i != j)
var savingObj = {saving:calculateSaving(tours[i],tours[j]), tourA: i, tourB: j};
allPossibilities.push(savingObj);
}
}
allPossibilities.sort(function(a, b){
return b.saving-a.saving
})
document.getElementById("demo3").innerHTML = "success";
return allPossibilities;
}
//Initialize Array
var tours = [];
tours.push([0,1,2,3,0]);
tours.push([0,4,5,6,0]);
tours.push([0,7,8,0]);
tours.push([0,9,10,0]);
//BUG
document.getElementById("demo1").innerHTML = tours.join('\n'); // Shows array correctly
var allSavings = calculateAllSavings(); //BUG APPEARS HERE
document.getElementById("demo2").innerHTML = tours.join('\n'); // Doesn't show anything
Edit Solved:
combine() was overwriting the original tours[].
by doing the combining with cloned tours, the original was left untouchted.
function combineTours(tourA, tourB){
var tour1 = tourA.slice(0);
var tour2 = tourB.slice(0);
tour1.pop();
tour2.shift();
return tour1.concat(tour2);
}
Thanks to everyone who helped me
Well, in combineTours function you're calling .pop() method on one array and .shift() method on another, which removes one element from each of these arrays. In calculateAllSavings you're calling calculateSaving in a loop and it's calling combineTours, so you're effectively removing all elements from the sub-arrays.
Maybe you should just remove these lines from combineTours:
tourA.pop();
tourB.shift();
For the future: use console.log() for debugging, it could help you identify the issue.
Can you try this?
for(var i = 0; i < tours.length; i++){
for(var j = 0; j < tours[i].length; j++){
if(i != j)
var savingObj = {saving:calculateSaving(tours[i],tours[j]), tourA: i, tourB: j};
allPossibilities.push(savingObj);
}
}
Apart from this, you can also debug and see if your document.getElementById("demo2").innerHTML = tours.join('\n'); line actually gets executed. You may be running an infinite loop. Try and debug your code using chrome developer tools.

create an array from different objects

I've sent data from server side with socket.io :
for (i = 0; i<rows.length; i++) {
socket.emit('Switch', {eqid:rows[i].EquipmentID,eqroom:rows[i].Name});
}
and in the client side :
socket.on('Switch', function (data) {
console.log(data.eqid);
}
and what I get is :console log and when I do console.log(data.eqid[0] I get undefined
so I want to get an array [120336,120337..]
I've tried also to send an array from the beginning in the server side :
for (i = 0; i<rows.length; i++) {
var test=[];
test.push(rows[i].EquipmentID);
}
console.log(test);
console.log gives me the last equipmentID only [120339
console.log gives me the last equipmentID only [120339
Because you are redefining rows array in every iteration.
Try this:
var ids = [];
var names = [];
for (var i = 0; i < rows.length; i++) {
ids.push(rows[i].EquipmentID);
names.push(rows[i].Name);
}
socket.emit('Switch', {eqid: ids, eqroom: names});

Categories