When using different variables, both arrays get modified - javascript

So I was doing a little search engine for Google Sheets and I didn't want it to be case sensitive, so I make it declare "RealComments" as the actual content to be retrieved and then proceed to lowercase the "Comments" array row by row on the main loop.
It sounds to me like a no brainier that it should work, they are different variables and I'm returning the RealComments, not the Comments. But some kind of weird quantum entanglement is going on in my code because no matter how I declare it, every time I apply toLowecase() to either the RealComments or Comments arrays both get modified.
I have no clue why that is or how to fix it. Here's the full code:
/**
* Searches for relevant questions and answers
*
* #param {cell} Keywords Cell with comma separated list
* #param {cell} Query Cell with text in question format
* #param {cell} Type Validation cell with options, leave "Any" for no filter
* #param {column} TypeOfComment Array with the type of question column
* #param {array} Comments Array with the questions and answers in two columns
* #param {column} ScreenshotLinks Array with the screenshot link column
* #return Your answer. :)
* #customfunction
*/
function SearchQuery(Keywords,Query,Type,TypeOfComment,Comments,ScreenshotLinks) {
if(Keywords==""){
return "Please type your query/keywords above for results to be displayed here."
}
var ResultArray = [];
var Score = 0;
var MinimumScore = 2;
var MinimumScorePosition = 0;
var keywords = [];
var querywords = [];
var RealComments = Comments;
for(rows in RealComments){
RealComments[rows].push(ScreenshotLinks[rows][0]);
}
var RemaneingKeywords = CleanPunctuation(Keywords);
var RemaneingQuery = CleanPunctuation(Query);
var NextSpace = RemaneingKeywords.indexOf(' ');
while(NextSpace != -1){
keywords.push(RemaneingKeywords.substr(0,NextSpace));
RemaneingKeywords = RemaneingKeywords.substr(NextSpace+1,RemaneingKeywords.length);
NextSpace = RemaneingKeywords.indexOf(' ');
}
keywords.push(RemaneingKeywords);
NextSpace = RemaneingQuery.indexOf(' ');
while(NextSpace != -1){
querywords.push(RemaneingQuery.substr(0,NextSpace));
RemaneingQuery = RemaneingQuery.substr(NextSpace+1,RemaneingQuery.length);
NextSpace = RemaneingQuery.indexOf(' ');
}
querywords.push(RemaneingQuery);
for(rows in Comments){
Comments[rows][0] = Comments[rows][0].toLowerCase(); //Investigate lowercase glitch
Comments[rows][1] = Comments[rows][1].toLowerCase();
if(Type=="Any"||TypeOfComment[rows]==Type){
Score = 0;
for(keyword in keywords){
if(Comments[rows][0].indexOf(keywords[keyword])!=-1||Comments[rows][1].indexOf(keywords[keyword])!=-1){
Score = Score+10;
}
}
for(words in querywords){
if(Comments[rows][0].indexOf(querywords[words])!=-1||Comments[rows][1].indexOf(querywords[words])!=-1){
Score = Score+1;
}
}
if(ResultArray.length<20 && Score>2){
ResultArray.push(RealComments[rows]);
ResultArray.push(Score);
MinimumScore = FindMinimumScore(ResultArray);//Math.min.apply(null,ResultArray);
}
else{if(Score>MinimumScore){
MinimumScorePosition = ResultArray.indexOf(MinimumScore);
ResultArray.splice(MinimumScorePosition-1,2);
ResultArray.push(RealComments[rows]);
ResultArray.push(Score);
MinimumScore = FindMinimumScore(ResultArray);
}}
}
}
var ScoresForSorting = []; //Sorting the responses here
for(i=0;i<10;i++){
if(ResultArray[i+1]==undefined){ScoresForSorting.push(-2);}
else{ScoresForSorting.push(parseInt(ResultArray.splice(i+1,1)));}
}
var ResponseOrder = [];
for(i=0;i<10;i++){
MinimumScorePosition = ScoresForSorting.indexOf(Math.max(ScoresForSorting[0],ScoresForSorting[1],ScoresForSorting[2],ScoresForSorting[3],ScoresForSorting[4],ScoresForSorting[5],ScoresForSorting[6],ScoresForSorting[7],ScoresForSorting[8],ScoresForSorting[9]));
ResponseOrder.push(MinimumScorePosition);
ScoresForSorting[MinimumScorePosition]=-3;
}
var SortedResultArray = [];
for(results in ResponseOrder){
SortedResultArray.push(ResultArray[ResponseOrder[results]]);
}
if(SortedResultArray[0]==undefined){SortedResultArray = []; SortedResultArray.push("Sorry, No Result Was Found To Your Search. ) : ");}
return SortedResultArray
}
function FindMinimumScore(ResultArray){
return Math.min(ResultArray[1],ResultArray[3],ResultArray[5],ResultArray[7],ResultArray[9],ResultArray[11],ResultArray[13],ResultArray[15],ResultArray[17],ResultArray[19])
}
function CleanTwoLetterWords(words){
var badwords = ["do","in","at","it","of","as","be","if","or","we","by","an","or","no","my","vs"];
for(badword in badwords){words = words.replace(badwords[badword],"");}
return words
}
function CleanThreeLetterWords(words){
if(parseInt(words)>9){return ""} //remove numbers
var badwords = ["and","for"];
for(badword in badwords){words = words.replace(badwords[badword],"");}
return words
}
function CleanPunctuation(words){
words = words.toLowerCase();
var badlettergroup = ["{","}",",",":","+","-","™","®","?","!","(",")","'"];
for(letter in badlettergroup){while(words.indexOf(badlettergroup[letter]) != -1){words = words.replace(badlettergroup[letter]," ");}}
return words
}
function MakeThingsSingular(words){
var exceptions = ["this"];
if(exceptions.indexOf(words) != -1){return words}
var wordl = words.length;
if(words.substr(wordl-1,wordl) == "s" && words.substr(wordl-2,wordl) != "ss"){return words.substr(0,wordl-1)}
return words
}
I wrote it all myself, but I don't think any of this is particularly brilliant so feel free to copy. Also, to suggest improvements if you have any. But most important of all, if you have any idea why the lines making the Comments array lowercased would be affecting RealComments and/or how to fix it, please let me know.
EDIT:
So after some more research and helpful answers I've tried declarying RealComments as:
var RealComments = [];
for(rows in Comments){
RealComments.push(Comments[rows]);
}
On which case the glitch persists.
var RealComments = [...Comments];
Which returns a syntax error.
var RealComments = Comments.slice();
In which case the glitch still persists.
...
So basically, I still don't understand what's wrong with the code, commenting out the either of the lowercase lines affects the column you'd expect on the RealComments as if they were still linked.
Comments[rows][0] = Comments[rows][0].toLowerCase();
Comments[rows][1] = Comments[rows][1].toLowerCase();
So I guess this post if not yet solved... But thank you for all the replies up to now.

In javascript Array assignment creates reference not copy.
if you do
var a = [1,2,3,4];
var b = a;
b will be the reference for a. It means if you modify b, it is actually gonna modify a.
QUICK SOLUTION
in the line where you are doing
var RealComments = Comments;
Do this instead var RealComments = Comments.slice();
As long as Comments is an array slice method will return a new instance of Comments array. So modifying RealComments won't modify Comments anymore.

TheMaster pointed out that "slice() won't work, because Comments is not a array, but array of arrays.". After which the solution that did it for me was just using:
var newArray = JSON.parse(JSON.stringify(orgArray));
Which in my case was:
var RealComments = JSON.parse(JSON.stringify(Comments));
Thank you for all the help! I hope this helps other users.

Related

Why is this JavaScript looping twice in Zapier?

Here is a video that shows what I'm struggling with.
Here is a high level description of the process, followed by the actual JavaScript code I've written.
PROCESS
I built 2 Zaps that each run like this:
STEP 1 - Trigger (Cognito Form, which has repeating sections)
STEP 2 - JavaScript Code (which creates an Array of the form fields for ONE of the repeating sections, and separates them into individual strings using .split)
STEP 3 - Action (creates a ZOHO CRM Task for each string)
The first Zap runs on one of the sections of the form (Visits with Sales), and the second zap runs on a different section of the form (Visits without Sales). Each of these Zaps works fine on their own so I know the code is good, but I want to combine the two Zaps into one by combining the code.
I tried to combine by making five steps:
Trigger - Code1 - Zoho1 - Code2 - Zoho2
but the Zoho2 Tasks were each repeated
I then tried to re-order the five steps:
Trigger - Code1 - Code2 - Zoho1 - Zoho2
but now Zoho1 Tasks AND Zoho2 tasks were duplicated.
Finally I tried to combine ALL the JavaScript code into one:
Tigger - CombinedCode1+2 - Zoho 1 - Zoho2
but only the strings from Arrays in "Code2" are available to me when I go to map them in Zoho1.
CODE:
if (inputData.stringVSAccount == null) {
var listVSAccountArray = [];
var listVSUnitsArray = [];
var listVSPriceArray = [];
var listVSNotesArray = [];
var listVSVisitCallArray = [];
} else {
var listVSAccountArray = inputData.stringVSAccount.split(",");
var listVSUnitsArray = inputData.stringVSUnits.split(",");
var listVSPriceArray = inputData.stringVSPrice.split(",");
var listVSNotesArray = inputData.stringVSNotes.split(",");
var listVSVisitCallArray = inputData.stringVSVisitCall.split(",");
}
var output = [];
var arrayNos = listVSAccountArray.length;
var i = 0;
do {
var thisItemVSAccount = new String(listVSAccountArray[i]);
var thisItemVSUnits = new String(listVSUnitsArray[i]);
var thisItemVSPrice = new String(listVSPriceArray[i]);
var thisItemVSNotes = new String(listVSNotesArray[i]);
var thisItemVSVisitCall = new String(listVSVisitCallArray[i]);
var thisItemObj = {};
thisItemObj.itemVSAccount = thisItemVSAccount;
thisItemObj.itemVSUnits = thisItemVSUnits;
thisItemObj.itemVSPrice = thisItemVSPrice;
thisItemObj.itemVSNotes = thisItemVSNotes;
thisItemObj.itemVSVisitCall = thisItemVSVisitCall;
output.push({ thisItemObj });
i++;
} while (i < arrayNos);
//This is where the second zaps code is pasted in the combined version
if (inputData.stringOVAccount == null) {
var listOVAccountArray = [];
var listOVNotesArray = [];
var listOVVisitCallArray = [];
} else {
var listOVAccountArray = inputData.stringOVAccount.split(",");
var listOVNotesArray = inputData.stringOVNotes.split(",");
var listOVVisitCallArray = inputData.stringOVVisitCall.split(",");
}
var output = [];
var arrayNos = listOVAccountArray.length;
var i = 0;
do {
var thisItemOVAccount = new String(listOVAccountArray[i]);
var thisItemOVNotes = new String(listOVNotesArray[i]);
var thisItemOVVisitCall = new String(listOVVisitCallArray[i]);
var thisItemObj = {};
thisItemObj.itemOVAccount = thisItemOVAccount;
thisItemObj.itemOVNotes = thisItemOVNotes;
thisItemObj.itemOVVisitCall = thisItemOVVisitCall;
output.push({ thisItemObj });
i++;
} while (i < arrayNos);
I just started learning JavaScript this week, and sense that I am missing something obvious, perhaps a set of brackets. Thanks for any assistance
David here, from the Zapier Platform team. You're running into a confusing and largely undocumented feature where items after a code step run for each item returned. This is usually desired behavior - when you return 3 submissions you want to create 3 records.
In your case, it's also running subsequent unrelated actions multiple times, which sounds like it's undesired. In that case, it might be easier to have 2 zaps. Or, if "Zoho2" only ever happens once, put it first and let the branch happen downstream.
Separately, I've got some unsolicited javascript advice (since you mentioned you're a beginner). Check out Array.forEach (docs), which will let you iterate through arrays without having to manage as many variables (your own i every time). Also, try to use let and const over var when possible - it keeps your variables scoped as small as possible so you don't accidentally leak values into other areas.
​Let me know if you've got any other questions!
Just a note - you are declaring the same array variable output in both segments of your code block - the second declaration will be ignored.
Use the .forEach() method to iterate over your arrays, it will significantly cleanup you code. You also don't need to painstakingly construct the objects to be pushed into the output arrays.
This may not fix your issue but the code is far easier on the eye.
var listVSAccountArray = [],
listVSUnitsArray = [],
listVSPriceArray = [],
listVSNotesArray = [],
listVSVisitCallArray = [],
output = [];
if (typeof inputData.stringVSAccount === 'string') {
listVSAccountArray = inputData.stringVSAccount.split(',');
listVSUnitsArray = inputData.stringVSUnits.split(',');
listVSPriceArray = inputData.stringVSPrice.split(',');
listVSNotesArray = inputData.stringVSNotes.split(',');
listVSVisitCallArray = inputData.stringVSVisitCall.split(',');
}
// iterate over the array using forEach()
listVSAccountArray.forEach(function(elem, index){
// elem is listVSAccountArray[index]
output.push({
itemVSAccount: elem,
itemVSUnits: listVSUnitsArray[index],
itemVSPrice: listVSPriceArray[index],
itemVSNotes: listVSNotesArray[index],
itemVSVisitCall: listVSVisitCallArray[index]
})
})
//This is where the second zaps code is pasted in the combined version
var listOVAccountArray = [],
listOVNotesArray = [],
listOVVisitCallArray = [],
output_two = []; // changed the name of the second output array
if (typeof inputData.stringOVAccount === 'string') {
listOVAccountArray = inputData.stringOVAccount.split(',');
listOVNotesArray = inputData.stringOVNotes.split(',');
listOVVisitCallArray = inputData.stringOVVisitCall.split(',');
}
// iterate over the array using forEach()
listOVAccountArray.forEach(function(elem, index){
// elem is listOVAccountArray[index]
output_two.push({
itemOVAccount: elem,
itemOVNotes: listOVNotesArray[index],
itemOVVisitCall: listOVVisitCallArray[index]
});
});

Getting error .append is not a function

I am trying to split up a string on /* and then to split up those segments on */
So that I can separate out all of the comments as I want this code to be able to take all of the comments out of the string and then put it back together.
The problem is though I keep getting this .append error which I am pretty sure is because I have made a silly syntax error but I am struggling to find it and any help would be greatly appreciated.
JS
contents = "if for /* else */ . = == === /* return */ function"
var start = /\/\*/gi;
var end = /\*\//gi;
var commentsRemovedSec2 = [];
var commentsRemovedSec1 = contents.split(start);
console.log(commentsRemovedSec1);
for (var i = 0; i < commentsRemovedSec1.length; i++) {
var z = ""
var x = commentsRemovedSec1[i]
var y = x.split(start)
z = y[0]
commentsRemovedSec2.append(z);
};
console.log(commentsRemovedSec2);
Unfortunately .append() isn't an Array method.
Instead use the Array method .push().
commentsRemovedSec2.push(z)
The push() method adds one or more elements to the end of an array and
returns the new length of the array. MDN

Function to return a list - issue with filtering the output

I am trying to output only articles if authorsId = authorId.
Beside that the whole function works exactly as I want, here it is:
The general idea is to limit access to only own articles.
So, my question is: how do I limit the results to show only articles written by the owner of the page we are on (authorsId = authorId).
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
alert(authorsid) // authors of each article - it returns the proper values
alert(authorid) // author of the page we are on - it returns the proper value
var count = 0;
rel.options[x] = new Option(title, id, authorid); // lign that returns results
title = '';
id = '';
authorid = '';
}
}
I suspect the problem is when you try performing a conditional statement (if/then/else) that you are comparing a number to a string (or a string to a number). This is like comparing if (1 == "1" ) for example (note the double quotes is only on one side because the left would be numeric, the right side of the equation would be a string).
I added a test which should force both values to be strings, then compares them. If it still gives you problems, make sure there are no spaces/tabs added to one variable, but missing in the other variable.
Also, I changed your "alert" to output to the console (CTRL+SHIFT+J if you are using firefox). The problem using alert is sometimes remote data is not available when needed but your alert button creates a pause while the data is being read. So... if you use alert, your code works, then you remove alert, your code could reveal new errors (since remote data was not served on time). It may not be an issue now, but could be an issue for you going forward.
Best of luck!
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
console.log("authorsid = "+authorsid); // authors of each article - it returns the proper values
console.log("authorid = "+authorid); // author of the page we are on - it returns the proper value
if( authorsid.toString() == authorid.toString() )
{
rel.options
var count = 0;
console.log( authorsid.toString()+" equals "+authorid.toString() );
rel.options[rel.options.length] = new Option(title, id, authorid); // lign that returns results
}
else
{
console.log( authorsid.toString()+" NOT equals "+authorid.toString() );
}
title = '';
id = '';
authorid = '';
}
Did you check the console for messages? Did it correctly show authorid and authorsid?
I have edited the script and made a couple of additions...
The console will tell you if the conditional check worked or not (meaning you will get a message for each record). See the "if/else" and the extra "console.log" parts I added?
rel.options[x] changed to equal rel.options[rel.options.length]. I am curious on why you set rel.options.length=0 when I would instead have done rel.options=new Array();

Loop, get unique values and update

I am doing the below to get certain nodes from a treeview followed by getting text from those nodes, filtering text to remove unique and then appending custom image to the duplicate nodes.
For this I am having to loop 4 times. Is there is a simpler way of doing this? I am worried about it's performance for large amount of data.
//Append duplicate item nodes with custom icon
function addRemoveForDuplicateItems() {
var treeView = $('#MyTree').data('t-TreeView li.t-item');
var myNodes = $("span.my-node", treeView);
var myNames = [];
$(myNodes).each(function () {
myNames.push($(this).text());
});
var duplicateItems = getDuplicateItems(myNames);
$(myNodes).each(function () {
if (duplicateItems.indexOf($(this).text()) > -1) {
$(this).parent().append(("<span class='remove'></span>"));
}
});
}
//Get all duplicate items removing unique ones
//Input [1,2,3,3,2,2,4,5,6,7,7,7,7] output [2,3,3,2,2,7,7,7,7]
function getDuplicateItems(myNames) {
var duplicateItems = [], itemOccurance = {};
for (var i = 0; i < myNames.length; i++) {
var dept = myNames[i];
itemOccurance[dept] = itemOccurance[dept] >= 1 ? itemOccurance[dept] + 1 : 1;
}
for (var item in itemOccurance) {
if (itemOccurance[item] > 1)
duplicateItems.push(item);
}
return duplicateItems;
}
If I understand correctly, the whole point here is simply to mark duplicates, right? You ought to be able to do this in two simpler passes:
var seen = {};
var SEEN_ONCE = 1;
var SEEN_DUPE = 2;
// First pass, build object
myNodes.each(function () {
var name = $(this).text();
var seen = seen[name];
seen[name] = seen ? SEEN_DUPE : SEEN_ONCE;
});
// Second pass, append node
myNodes.each(function () {
var name = $(this).text();
if (seen[name] === SEEN_DUPE) {
$(this).parent().append("<span class='remove'></span>");
}
});
If you're actually concerned about performance, note that iterating over DOM elements is much more of a performance concern than iterating over an in-memory array. The $(myNodes).each(...) calls are likely significantly more expensive than iteration over a comparable array of the same length. You can gain some efficiencies from this, by running the second pass over an array and only accessing DOM nodes as necessary:
var names = [];
var seen = {};
var SEEN_ONCE = 1;
var SEEN_DUPE = 2;
// First pass, build object
myNodes.each(function () {
var name = $(this).text();
var seen = seen[name];
names.push(name);
seen[name] = seen ? SEEN_DUPE : SEEN_ONCE;
});
// Second pass, append node only for dupes
names.forEach(function(name, index) {
if (seen[name] === SEEN_DUPE) {
myNodes.eq(index).parent()
.append("<span class='remove'></span>");
}
});
The approach of this code is to go through the list, using the property name to indicate whether the value is in the array. After execution, itemOccurance will have a list of all the names, no duplicates.
var i, dept, itemOccurance = {};
for (i = 0; i < myNames.length; i++) {
dept = myNames[i];
if (typeof itemOccurance[dept] == undefined) {
itemOccurance[dept] = true;
}
}
If you must keep getDuplicateItems() as a separate, generic function, then the first loop (from myNodes to myNames) and last loop (iterate myNodes again to add the span) would be unavoidable. But I am curious. According to your code, duplicateItems can just be a set! This would help simplify the 2 loops inside getDuplicateItems(). #user2182349's answer just needs one modification: add a return, e.g. return Object.keys(itemOccurance).
If you're only concerned with ascertaining duplication and not particularly concerned about the exact number of occurrences then you could consider refactoring your getDuplicateItems() function like so:
function getDuplicateItems(myNames) {
var duplicateItems = [], clonedArray = myNames.concat(), i, dept;
for(i=0;i<clonedArray.length;i+=1){
dept = clonedArray[i];
if(clonedArray.indexOf(dept) !== clonedArray.lastIndexOf(dept)){
if(duplicateItems.indexOf(dept) === -1){
duplicateItems.push(dept);
}
/* Remove duplicate found by lastIndexOf, since we've already established that it's a duplicate */
clonedArray.splice(clonedArray.lastIndexOf(dept), 1);
}
}
return duplicateItems;
}

Javascript regular expressions for Query Builder

This may have been asked in the past but I couldnt find a suitable answer. What I am looking for is a method to extract parameters from an sql query such as below. The queries will always be an EXEC statement followed by the query name, and possible parameters.
Here is an example of what I may recieve
EXEC [dbo].[myProcedure] #Param1
This could also be as follows
EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3
Those are the only types of queries that the input will take. As for why I am doing this, well thats another question all together, and I am pretty set on going down this route.
What I am looking for is to be able to take the above strings and produce an array of values such as
['#Param1','#Param2','#Param3',....]
I originally tried to just parese using a simple while statement but I seem to have huge issues there.
I hope this question makes sense,
Cheers,
Nico
[Edit]
Sorted this by using the following statement
function eParams(e) {
var i = e.indexOf('#');
if (i <= 0)
return;
e = e.substring(i);
var p = e.split(',');
var eList = [];
var s = '';
for (var i = 0, j = p.length - 1; i <= j; i++) {
var sP = p[i].trim();
if (sP.indexOf('#') < 0)
continue;
eList.push(sP);
}
}
var str = 'EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3';
(str).match(/(#[^\s,]+)/g);
will return an array.
var s = "EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3";
var i = s.indexOf('#');
var a = s.substr(i).split(/\s*,\s*/);
(error checking omitted)

Categories

Resources