I dont understand what is wrong with this code - discord

My code is used so it generates random rarities based on how many you want to generate but I keep getting the syntax error:
i is not defined
With this code:
var rarities = [
'Common',
'Uncommon',
'Rare',
'Epic',
'Legendary',
'Exotic',
'Mythic'
]
let rarity = rarities[Math.floor(Math.random() * rarities.length)
function generateRarity(length, times){
let numbers = [];
for(i=0; i < times; i++){
let number = Math.floor(Math.random() * length)
numbers.push(number)
}
return numbers;
}
let indexArray = generateRarity(rarities.length, args)
let generatedRarities = [];
indexArray.forEach(index => generatedRarities.push(rarities[index]))
sentrarities = "#".join(generatedRarities)
await message.reply(sentrarities)

You get this error only because of a typo. When you are declaring let rarities, you are missing an ] at the end of it. JS then tries to include the function in it but then finds out that it can't so the error comes. All you have to do is change your code to:
var rarities = [
'Common',
'Uncommon',
'Rare',
'Epic',
'Legendary',
'Exotic',
'Mythic'
]
let rarity = rarities[Math.floor(Math.random() * rarities.length)]
function generateRarity(length, times) {
let numbers = [];
for (i = 0; i < times; i++) {
let number = Math.floor(Math.random() * length)
numbers.push(number)
}
return numbers;
}
let indexArray = generateRarity(rarities.length, args)
let generatedRarities = [];
indexArray.forEach(index => generatedRarities.push(rarities[index]))
sentrarities = "#".join(generatedRarities)
await message.reply(sentrarities)

Related

Object at different indexes when exporting in json

It happens that I am creating an object in Node JS and mssq, however some arrays are put in position 0, 0, and other arrays are put in [0], 1, 2, How can I find out what is causing this behavior?
Behavior 1
Query
var branchOfficesDTO = [];
var branchs = await pool.request().input('idUser', idUser).query(queryGetBranchsByUser);
for (let i = 0; i < branchs.recordset.length; i++) {
var categories = await pool.request().input('id', branchs.recordset[i].id).query(queryGetCategoriesByBranch);
let userDTO = {
categories: categories.recordset
}
branchOfficesDTO.push(branchOfficeDTO);
}
Result
Behavior 2
Query
var usersDTOByID = [];
var users = await pool.request().input('id', id).query(queryGetUserById);
for (let i = 0; i < users.recordset.length; i++) {
var categories = await pool.request().input('idUser', users.recordset[i].id).query(queryGetCategoriesByUser);
let userDTO = { categories: categories.recordset }
}
usersDTOByID.push(userDTO);
Result
I need the second behavior, help

Output variables one by one from array

how do I pull variables from array one by one? I want to make a card with one saying Zlin, second Praha, etc... The way it works now is that it outputs all of them at once 4x. Thank you.
const KartyLoop = () => {
var mesta = ['Zlin','Praha','Ostrava','Brno']
var lokace = []
for (var i=0; i < mesta.length; i++)
{
lokace += mesta + "\n"
}
return (<Text>{lokace}</Text>);
}
Your code pushes the array itself and not its values.
If I understand correctly you want to copy an array.
You would want to do this.
const KartyLoop = () => {
var mesta = ['Zlin','Praha','Ostrava','Brno']
var lokace = []
for (var i=0; i < mesta.length; i++)
{
lokace += mesta[i] + "\n"
}
return (lokace);
}

How to fix 'Cannot convert Array to Object[][]' error in Google Apps Script

I'm attempting to get a list of all groups and all members of a group to be posted to a spreadsheet titled 'allGroups'. However, whenever I try to print the Array to the sheet I'm getting the error that says I can't convert the Array to an Object.
I've tried setting the array to be different sizes, changing the range so that it's more specific, and changing the code so that the group name is posted first (clearing the Array) and then moving from there but it hasn't worked.
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'google.com',
maxResults: 100,
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push(member.email);
outputSheet.getRange(u+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
}
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
Expected results would be that a list of groups would populate across row 1, and the list of member's emails would appear below each group. Currently once I get to
outputSheet.getRange(u+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
it tells me that can't convert the Array to an Object and fails.
EDIT
I've managed to get it working thanks to AMolina, Ross, and Cooper. This is the code I've got now:
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
var p = 0;
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'google.com',
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push([member.email]);
}
if(membersPageToken != undefined) {
p = p + 200;
} else { p = 0; }
Logger.log(p);
outputSheet.getRange(p+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
It also is able to handle when there's more than 200 members in a group.
Try this:
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'sbtagent197.eu',
maxResults: 100,
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push([member.email]);
}
// This is where I made the change, moving this line outside the inner loop.
outputSheet.getRange(1, i+1, listArray.length, listArray[0].length).setValues(listArray);
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
I modified the code you had by changing the location of the outputSheet.getRange(1, i+1, listArray.length, listArray[0].length).setValues(listArray); line, you were calling it several times during the loop, which was causing the title to appear many times. basically, you were writing the block of group_name -> members over and over, one row lower every time, so it looked like you were writing the title a bunch of times when it was the whole thing.
The edited code sets the values once when the array is complete, it will write the name of the group in the first row and the members in the rows below it. Moving forward I would suggest you consider #Cooper 's advice, using getValues() and setValues() can make working with sheets much easier.

How can I do to aggregate count function return a number not an array

I try to count number of each article but the result is not what I want
This is my code
var nameWebsites = await Article.distinct("website.name");
var idWebsites = await Article.distinct("website.id");
var numberArticle = [];
var result = [];
for(var i = 0; i < nameWebsites.length; i++) {
await Article.aggregate([
{ $match: {"website.id": idWebsites[i]}},
{ $count: "count"}
], function(err, result){
numberArticle.push(result);
});
}
for(var i = 0; i < nameWebsites.length; i++) {
result.push({"id":idWebsites[i], "name":nameWebsites[i], "number_article": numberArticle[i]});
}
And this is a part of result
{"data":[{"id":1,"name":"Dan tri","number_article":[{"count":52952}]},...]}
I want the result like:
{"data":[{"id":1,"name":"Dân trí","number_article":52952},...]}
Instead of grabbing the entire results of numberArticle[i], get the just count of the first object in the array.
for(var i = 0; i < nameWebsites.length; i++) {
result.push({
id: idWebsites[i],
name: nameWebsites[i],
number_article: numberArticle[i][0].count,
});
}
var objectArray = {"data":[{"id":1,"name":"Dân trí","number_article":52952}]}
Then you can use
objectArray.data.length

converting an object to an array in angular2 typescript

I have an object within an object and i would like to convert the inner one to a string separated comma but it generates an infinite loop
After an observable http request am getting the data this way
this._categoryService.getChecklistCategories()
.subscribe(
res => {
this.categories = res;
let newitem:string[];
for(var i=0; i<res.length; i++){
this.categories.map((category, i) => category.no = i+1);
var obj = res[i].assigned; //an obect.
console.log(obj[0]); //get the first index
}
})
The above console.log(obj[0]) generates
I would like to create a string of truck_subtype and append it to this.categories
I have tried the following
res => {
this.categories = res;
let newitem:string[];
for(var i=0; i<res.length; i++){
this.categories.map((category, i) => category.no = i+1);//this adds no i,2,3...
var obj = res[i].assigned; //array item
let stringArray: Array<any> = [];
for(var i=0; i<obj.length; i++){
stringArray.push(obj[i].truck_subtype);
}
this.categories.map((category, i) => category.assigned= stringArray)
}
}
The above generates an infinite loop and fails to add the string of array to this.categories
Where am i wrong
May be the i variable that are declared four times (in for's and in map's), I think your index never gets to the res.length because when you use map you are resigning it.
Try to change the i's inside map to another name like i2..., and test it to see if the loops goes away.
res => {
this.categories = res;
let newitem:string[];
for(var i=0; i<res.length; i++){
this.categories.map((category, i2) => category.no = i+1);//this adds no i,2,3...
var obj = res[i].assigned; //array item
let stringArray: Array<any> = [];
for(var i3 =0; i<obj.length; i++){
stringArray.push(obj[i3].truck_subtype);
}
this.categories.map((category, i4) => category.assigned= stringArray)
}
}

Resources