I have created a code in node.js, which use mongoDB. Everything is working fine, but when I use nested loop, it break and don't return the proper values.
DB1.find({},function(error,fetchAllDB1) {
var mainArray = new Array();
for (var i in fetchAllDB1) {
if(fetchAllDB1[i].name) {
var array1 = new Array();
var array2 = new Array();
array1['name'] = fetchAllDB1[i].name;
array1['logo'] = fetchAllDB1[i].logo;
array1['desc'] = fetchAllDB1[i].desc;
DB2.find({is_featured:'1', brand_id: fetchAllDB1[i]._id}, function(error,fetchDB2) {
for (var p in fetchDB2) {
var pArr=[];
pArr['_id'] = fetchDB2[p]._id;
pArr['name'] = fetchDB2[p].name;
pArr['sku'] = fetchDB2[p].sku;
pArr['description'] = fetchDB2[p].description;
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
console.log(pArr);
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
array2[p]=pArr;
}
array1['pp']= array2;
});
mainArray[i]=array1;
}
}
console.log('######### LAST #########');
console.log(mainArray);
console.log('######### LAST #########');
});
In my console message its showing
console.log('######### LAST #########');
All Values
console.log('######### LAST #########');
After that
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
All Values;
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
I want to use async in my code, so that all data fetching occur as below:
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
Your code is very confusing and overly complicated.
What you should do is (psuedo code):
DB1.find(foo) // returns one result
.then(getFromDB2);
function getFromDB2 (res){
return DB2.find(res); // make a query here with mongo drivers `$in`
}
Mongodb : $in operator vs lot of single queries
Related
I've been trying without success to get unique values from an array, after creating the array from getRespondentEmail in google apps script. I've tried to use the set method, the forEach etc for this and each time it returns an empty array or empty curly brackets. This is a sample of my code:
function test(){
var form = FormApp.openById('...');
form.setCollectEmail(true);
var formResponses = form.getResponses();
var getEmails = [];
var uniqueResponses = [...new Set(getEmails)];
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var oneEmail = formResponse.getRespondentEmail();
getEmails.push(oneEmail);
}
Logger.log(uniqueResponses);
}
Does anyone know what the problem might be? I'm stuck. Thank you so much.
In your script, how about the following modification?
Modified script:
function test(){
var form = FormApp.openById('...');
form.setCollectEmail(true);
var formResponses = form.getResponses();
var getEmails = [];
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var oneEmail = formResponse.getRespondentEmail();
getEmails.push(oneEmail);
}
var uniqueResponses = [...new Set(getEmails)];
Logger.log(uniqueResponses);
}
In your script, when var uniqueResponses = [...new Set(getEmails)] is run, getEmails has no value. By this, your issue occurs. In this modification, var uniqueResponses = [...new Set(getEmails)] is used after getEmails has the values. By this, the duplicated values are removed.
Reference:
Set
I have a google sheet. I am try to get all tab names in to array. I used this code.
function allTabNames() {
try{
var out = new Array();
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i =0; i<sheets.length; i++) out.push([sheets[i].getName()]);
Logger.log(out);
Logger.log(out.length);
return out
}
catch (er){
Logger.log(er);
}
}
It's working correctly. Now I want to remove some tab names. I created a new array using the tab names I want to remove.
var duparray = ["Sheet1", "newRoad147", "Sheet2", "Sheet3", "Sheet4","Sheet5", "Sheet6"];
When I run the first mentioned code I will get this. The array "out".
[[Sheet1], [newRoad147], [Sheet2], [Sheet3], [Sheet4], [Sheet5], [Sheet6], [Sheet7], [AddData], [WCO069], [WCO065], [WCO149], [WCO141], [WCO158], [BarChart], [Sheet11]]
I am trying to remove the common element in these two arrays. For that I used the following code. But it did not go well.
function allTabNames() {
try{
var out = new Array();
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i =0; i<sheets.length; i++) out.push([sheets[i].getName()]);
Logger.log(out);
Logger.log(out.length);
//return out
var duparray = ["Sheet1", "newRoad147", "Sheet2", "Sheet3", "Sheet4","Sheet5", "Sheet6"];
var outx = out.filter( function( el ) {
return duparry.indexOf( el ) < 0;
} );
}
catch (er){
Logger.log(er);
}
Logger.log(outx);
}
The order of these tabs can be changed. That is why I try to remove the element using the specific names of the elements in the array. Then we hope to create a dropdown list of elements in this new array using data validation.
Get Sheet names and omit not included
function getTabName() {
const ss = SpreadsheetApp.getActive();
const nincl = ['Sheet1','Sheet2'];//not included
const shts = ss.getSheets().filter(sh => !~nincl.indexOf(sh.getName())).map(sh => sh.getName());
ss.getSheetByName('Sheet5').getRange("C5").setDataValidation(SpreadsheetApp.newDataValidation().requireValueInList(shts,true).build());
return shts;
}
I have this data inside my controller form:
$scope.reports = [
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
},
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
}
];
The above data is array of objects, I want them to convert in array. I used this code below to convert them in array:
var details=[];
for(var index in $scope.reports){
var tripcode = $scope.reports[index].tickettripcode;
var dateOfDepature = $scope.reports[index].departuredate.split('-');
details.push(tripcode, dateOfDepature[2]);
}
if(details[tripcode][dateOfDeparture[2]]){
details[tripcode][dateOfDeparture[2]] = details[tripcode][dateOfDeparture[2]] +1;
}
else {
details[tripcode][dateOfDeparture[2]] =1;
}
The code is not working fine with me and I do not know why. I have a doubt if I am doing array manipulation in a right way. I have error dateOfDeparture is not defined. I already defined the dateOfDeparture so why I getting this error. I just wanted to get the output which looks like this:
details = Array (
[3] =>Array
(
[10] =>2
)
)
The [3]is tickettripcode and [10] is the day of depaturdate. The 2 means number of departuredate in that date.
Any help would be much appreciated.
This is the link of my fiddle : https://jsfiddle.net/n1bw2u36/
Thanks in advance!
Unfortunately there are a lot of things you should learn about javascript.
By the way, I would expect that you will get what you want with the code like this.
var reports = [
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
},
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
}
];
var table = {};
for (index=0; index<reports.length; index++){
var tripcode = reports[index].tickettripcode;
var dateOfDepature = reports[index].departuredate.split('-');
var date = dateOfDepature[2];
var map = table[tripcode];
if (map===undefined){
map = {};
table[tripcode] = map;
}
if (map[date]===undefined){
map[date] = 0;
}
map[date]++;
}
You can use "table" like this.
console.log(table);
console.log(table[3][10]);
I’m new to Backbone, but I’ve successfully been able to define an array like this on one of my models:
buildMyArray: function() {
var self = this;
var myArray = {};
window.myLibrary.getStuff('myParameter', function(myStuff) {
for (var myKey in myStuff) {
if (myStuff.hasOwnProperty(myKey)) {
var myValue = myStuff[myKey];
myArray[myKey] = myValue;
}
}
self.set({ myArray: myArray });
});
}
However, how can I access that array from other properties? In other words, I want to do something like this:
checkArrayStuff: function(arrayKey) {
//loop through myArray and check value for arrayKey.
//var myArray1 = self.get(myArray);
//var myArray2 = this.get(myArray);
//var myArray3 = myArray;
//var myArray4 = this.myArray;
//var myArray5 = self.get('myArray');
//var myArray6 = this.get('myArray');
var myArray7 = self.myArray;
var can = myArray7[arrayKey];
return can;
}
I’ve tried several variations of self, this, with-and-without-quotes, with-and-without get-method, etc.
I guess you would have to do this
checkArrayStuff: function(arrayKey) {
return this.get('myArray')[arrayKey];
}
this.get('myArray') should work but it looks like your window.myLibrary.getStuff function is asynchronous. That means myArray won't be set until some time after buildMyArray returns. If you give us more context we can make a better recommendation of how to address this such as having buildMyArray call checkArrayStuff after it's done the .set(..) or having buildMyArray return a promise
I'm trying to write a function where I can specify any amount of array, and the return value will be an array containing the contents of all of the specified arrays.
I've done this, but it seems like a really slow and ugly way of doing it:
var ar1:Array = [1,2,3,4,5,6,7,8,9];
var ar2:Array = ['a','b','c','d','e','f','g','h'];
function merge(...multi):Array
{
var out:String = "";
for each(var i:Array in multi)
{
out += i.join(',');
}
return out.split(',');
}
trace(merge(ar1, ar2));
Is there an inbuilt and more efficient / nice way of achieving this? The result does not need to be in the same order as the input - completely unsorted is fine.
You can use concat.
If the parameters specify an array, the elements of that array are concatenated.
var ar1:Array = [1,2,3,4,5,6,7,8,9];
var ar2:Array = ['a','b','c','d','e','f','g','h'];
var ar3:Array = ['i','j','k','l'];
var ar4 = ar1.concat(ar2, ar3); // or: ar1.concat(ar2).concat(ar3);
To make a single array out of a 2 dimensional array you can use this function:
private function flatten(arrays:Array):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
// call
var ar4 = [ar1, ar2, ar3];
var ar5 = flatten(ar4);
You can also use varargs to merge multiple arrays:
private function merge(...arrays):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
// call
var ar5 = merge(ar1, ar2, ar3);
I don't know if this method is faster than using loops, but it is a (fancy) quick way to merge 2 arrays. (and it works in Javascript and Actionscript)
var arr1:Array = [1,2,3,4,5]
var arr2:Array = [6,7,8,9,10]
arr1.push.apply(this, arr2); // merge
// arr1.push.call(this, arr2); // don't use this. see comment below
trace(arr1) // 1,2,3,4,5,6,7,8,9,10
function merge(...multi):Array
{
var res:Array = [];
for each(var i:Array in multi)
{
res = res.concat(i);
}
return res;
}
Didnt try it, but something like this would help you.