For loop ending after the first iteration - javascript

I'm trying to check which person to assign to each job using GAS. The function runs against an array that contains both: the person responsible for the client and his client list.
The code works fine when running for the first Client in the array, it adds the member and everything, so I know it's working. The problem is it only runs once, so if the client is "PR", it will add "lucasfogolin" as a member, but if its CLC, it won't check.
var clients = [{actor:'lucasfogolin',clients:'PR,CLC,TrĂ­via,Smart,MC,TTWO'},
{actor:'alfredorocha',clients:'FDV,IAB,IMDiva'}
]
My sorting function is below:
function sortActors(notification) {
//When a card is moved to the "Sorting list"
var card = new Notification(notification).movedCard('Sorting');
//Gets the cards name
var cardName = card.name();
for (var i = 0; i < clients.length; i+=1) {
//Creates an array from splitting the clients
var arrayClients = clients[i].clients.split(',');
for (var j = 0; j < arrayClients.length; j+=1) {
//Creates a REGEX to run against the card's name, not sensitive
var regex = new RegExp(arrayClients[j],'gi');
//Checks if the name of the client is in the name of the card
if(cardName.match(regex)[0] == arrayClients[j]) {
//Function that adds the actor to the card
addMembers(card,clients[i].actor)
}
}
}
return false;
}
addMembers function
function addMembers(card,members) {
//Makes an array from the members cited (if more than one is to be added)
var array = members.split(',');
//Runs a loop to add all members
for (var i = 0; i < array.length; i+=1) {
card.addMember(new Member({username: array[i]}));
}
}

change the code from
if(cardName.match(regex)[0] == arrayClients[j])
to this
if(cardName.match(regex) != null && cardName.match(regex)[0] == arrayClients[j])

In this part
//Checks if the name of the client is in the name of the card
if(cardName.match(regex)[0] == arrayClients[j]) {
You are checking element 0 of a regex string match, that's ok when you have a match but when you don't have a match cardName.match(regex) will return null and it is not possible to access element 0 of a null value. That could create problems.

Related

How can I delete array elements just once to add new ones with a for loop

What I am trying to do is:
set an array value (list) to another array (options).
If the user's input (searchVal) matches with a list value it will delete options, push this match, and then will keep pushing the next matches without deleting options again.
So according to the code below, if searchVal was "whatever", options should return: ["whatever", "whatevEver1"] but, instead, it returns: ["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]
Relevant code:
var list = ["whatever", "WhatEver1", "whatttever"];
var clear = 0;
var options = [];
for (var i=0 ; i < list.length ; i++)
{
options.push([list[i]]);
}
var searchVal = window.prompt(" ");
for (var i=0 ; i < list.length ; i++)
{
if (list[i].toLowerCase().includes(searchVal.toLowerCase())) {
if (clear == 0) {
options.length = 0;
}
options.push([list[i]]);
}
clear++;
}
return options;
Js arrays are pass-by-reference. In order to make independent copy of array you need to use:
let options = JSON.parse(JSON.stringify(list));
I didnt try to implement this to your problem cause im too lazy but i think it might work.

JSON for-loop that ignores blank sub arrays

I am using p5 loadJSON to import data, the data gives an array with so many records and sub-arrays.
For example, data.records[i].form_values["94d5"] gives me a name.
I am currently using a for loop to go through data.records.length and give me an array of some key pieces of data relative to each record I want to see.
Problem:
I want to loop through the records and get the value of:
data.records[i].form_values["94d5"].choice_values["0"], but some records don't have form_values["94d5"], for example. I just want to skip empty sections (leave undefined like empty items) insted i get an error that choice_values is undefined.
My loop is:
function gotData(data){
var i = 0;
var statusFind = data.records[i].status;
for(i = 0; i < data.records.length; i++) {
var returned = [data.records[i].form_values["6f71"], data.records[i].form_values.b059, data.records[i].form_values["94d5"], data.records[i].form_values.b62d, data.records[i].form_values["3493"].choice_values["0"], data.records[i].status, data.records[i].form_values.af80];
for (j = 0; j < returned.length; returned++){
if (returned[j] == searchKey) {
var result = [returned[0], returned[1], returned[2], returned[3], returned[4], returned[5], returned[6]];
array.push(result);
write();
}
}
}
}

Accessing Connected Vertices in OrientDB Javascript Functions

I'm attempting to use the build in Functions in OrientDB studio to group Workstations that aren't in use by a Person. The query to get these vertices works fine but I'm trying to avoid Traverse as it is very slow - too slow to be used in production. Instead of iterating through each free station and grouping it together with all it's neighbours, keeping each grouped 'named' with the smallest #rid in the set.
var groups = {}; //The list of groups of workpoints. The key is the lowest RID in the group
var mappedDesks = {}; //Every desk's RID is in this object with it's matching value being the group name they're in
//Get all Workpoints that don't have a Locale CURRENTLY_LOCATED_ON them
var freeDesks = db.query("SELECT FROM Workpoint WHERE #rid NOT IN (SELECT #rid FROM (SELECT EXPAND(OUT('CURRENTLY_LOCATED_ON').OUT('LOCATED_ON')) FROM Person) WHERE #class = 'Workpoint')");
//Iterate through all vacant Workpoints
for (var j=0; j < freeDesks.length; j++){
var baseNodeRid = freeDesks[j].getRecord().getIdentity().toString(); // The RID of the Workpoint
var baseNodeNumber = parseFloat(baseNodeRid.replace("#", "").replace(":",".")); // The RID converted to a number for comparisons. The lower RID takes precedence
var baseSanitized = baseNodeRid.replace(":","-") // Keys cannot contain colon so they are replaced with a dash
if (freeDesks[j].getRecord().field("out_NEIGHBOUR_OF") == null ) {
// Desks without neighbours can be put in a group on their own
groups[baseSanitized] = new Array();
groups[baseSanitized].push(baseNodeRid);
mappedDesks[baseSanitized] = baseSanitized;
} else {
//Iterate over all the desk's neighbours
for (var n = 0; n < freeDesks[j].getRecord().field("out_NEIGHBOUR_OF").length; n++){
//Convert the neighbour's RID to a number too
var nSanitized = n.replace(":","-");
if (parseFloat(n.replace("#", "").replace(":",".")) > baseNodeNumber ){
//The neighbour's node group is larger than the current one. This needs to be merged into the group with the smaller rid
//Move the desks from the neighbour's group into the base's group. If it has none then do nothing
var nGroup = groups[mappedDesks[nSanitized]]
if ( nGroup != null) {
groups[baseSanitized] = groups[baseSanitized].concat(nGroup);
//Change the mapping of each moved desk to the base's
for (var g = 0; g < nGroup.length; g++){
mappedDesks[nGroup[g]] = baseSanitized;
}
}
//Delete the reference to the old group
delete groups[mappedDesks[nSanitized]];
//Update the mappings for the desks dealt with
mappedDesks[nSanitized] = baseSanitized;
mappedDesks[baseSanitized] = baseSanitized;
} else {
// The neighbour is lower than the current desk so the desk should be merged into the neighbour's group
mappedDesks[baseSanitized] = nSanitized;
groups[nSanitized].push(baseNodeRid);
}
}
}
}
return groups;
My problem comes from accessing a vertex's neighbours. It correctly determines whether there are neighbours in the if statement return freeDesks[j].getRecord().field("out_NEIGHBOUR_OF") but I want to be able to get each neighbour's #rid so I can sort the #rids into groups.
freeDesks[j].getRecord().field("out_NEIGHBOUR_OF") returns the edge record but I dont seem to be able to get the "in" or "out" fields using the field() method (not found on this object) or accessing it as an array [].
[
{
"#type": "d",
"#rid": "#34:18176",
"#version": 6,
"#class": "NEIGHBOUR_OF",
"out": "#16:13",
"in": "#16:1408",
"#fieldTypes": "out=x,in=x"
}
]
Can you help be get a list/array of the neighbour #rids so I can iterate over them with the rest of the code?
Cheers!
A simpler example to understand what you can do:
create class Person extends V
create class IsNeighbour extends E
create vertex Person set name = 'P1' // 12:0
create vertex Person set name = 'P2' // 12:1
create vertex Person set name = 'P3' // 12:2
create edge IsNeighbour from #12:0 to #12:1
create edge IsNeighbour from #12:0 to #12:2
Define this Javascript Function:
var gdb = orient.getGraphNoTx();
var v = gdb.command("sql", "select from " + personRID);
var neighbours = v[0].getRecord().field("out_IsNeighbour").iterator();
var result = [];
while(neighbours.hasNext()){
var neighbour = neighbours.next();
result.push(neighbour.field("in"));
}
return result;
like this:
And then you can:
select getNeighbours("#12:0")

how to check a string against elements in an array

I am using the twitter stream api. I am currently using follow & track parameters but the API combines them with an OR and I want to combine them with an AND. The only way logically to do this is to manually check that the tweet contains a userID# in my array of userIDs to follow and the tweet text contains a keyword from my array of keywords to track.
I have converted the tweet object and tweet.text object into a JSON string like this:
var tweetText = JSON.stringify(tweet.text);
var tweetObject = JSON.stringify(tweet);
I want an if statement like this:
if tweetObject == a value in tracked ids array && tweetText == a value in tracked words array
do the rest of my code
How can I achieve this? I tried to use .indexOf() but that takes only one parameter so I could say:
if(tweetObject.indexOf("12345678") > -1 && tweetText.indexOf("spotify") > -1) {
do my code
}
But this is NOT what I want, I want it to go through the array and see if tweetObject and tweetText contain any of the array elements and if so do the code
this is what I have:
// start twitter
t.stream(
"statuses/filter",
{follow: trackedHandles, track: trackedWords, lang: "en" },
function(stream) {
stream.on('data', function(tweet) {
//convert tweet.text& tweet.entities into two strings
var tweetText = JSON.stringify(tweet.text);
var userName = JSON.stringify(tweet.entities);
var tweetObject = JSON.stringify(tweet);
var flag = false;
for (var x = 0; x < trackedHandles.length; x++) {
//console.log(trackedHandles[x].toString());
var searchParam = tweetObject.indexOf(trackedHandles[x].toString());
if(searchParam != -1) {
flag = true;
//console.log(searchParam);
//console.log(trackedHandles[x].toString());
//incriment the keywords, and store the keywords as keys in redis (as they appear in feed)
for (var i = 0; i < trackedWords.length; i++) {
if(tweetText.indexOf(trackedWords[i]) > - 1) {
// incriments added value to the word
console.log(trackedWords[i]);
redisClient.incr(trackedWords[i]);
}
}
//if tweetText does not contains "RT" & "#", print tweet to console.
if(tweetText.indexOf("RT") == -1 && tweetText.indexOf("#") == -1) {
//console.log(tweetText + "\r\n ");
//console.log(screen_name + "\r\n ");
//console.log(tweet);
}
}
}
});
}
);
Please help guys, this is for my senior project for my undergrad degree. I have most of the app it self complete, I just need this one piece because What I am trying to accomplish is to only stream tweets from specific users based on specific keywords. If you can think of a more appropriate title for this please let me know. Thanks in advance for any help!
Use a for or forEach loop
var tweetObjArr= [1,2,3,4,5];
var tweetIds = [7,3]
var flag = false;
for (var i = 0; i < tweetIds .length; i++) {
if(tweetObjArr.indexOf(tweetIds [i]) != -1) {
flag=true;
break;
}
}
Might be you want jQuery.inArray function like
if(jQuery.inArray("12345678", tweetObject)!==-1)

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

Categories