I'm trying to develop a random category Id generator function on nodejs. Firstly, I receive all the existing category Id's from my database and push them into a array then I generate a random integer(between boundaries) and I compare the random number with my cat id array. I use indexof() function to make the comparison but it always return true; What may be the problem. Here is my code;
var random = require("random-js")
var selectCategoryID = "SELECT id from category.category";
var catIdresult = client.querySync(selectCategoryID);
var catIdArray = [];
catIdresult.forEach(function (row) {
var catId = row.id;
catIdArray.push(catId);
});
var randomNum = new random()
var K = randomNum.integer(16777000, 16777999);
if(catIdArray.indexOf(K)){
console.log("Error, the id is : " + K);
}
else {console.log("Success, the id is : " + K)}
indexOf function returns the first index of an item inside an array or -1 if it didn't find the item. So your code should do this:
if (catIdArray.indexOf(K) === -1) {
//insert into db
}
else {
//error
}
You can also get all IDs by using a map function:
catIdArray = catIdresult.map(function(cat) {return +cat.id});
Related
I am new to GAS. I have built a 3D array and I would like to extract the nth column as a vector.
In this example, the 2D array is called "skillsarray" :
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("RV Partners");
var wsInfosPartners = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Infos Partners");
var skillsarray = wsInfosPartners.getRange(1, 1, 1, wsInfosPartners.getLastColumn()).getValues();
Then when entering a value in a cell of my sheet, I'd like to check if this value is part of my 1st row in the array. If yes, I'd like to store the correponding column in a new vector :
function onEdit (event) {
var celluleactive = event.range;
var valeur = celluleactive.getValue();
var ligne = celluleactive.getRow();
var colonne = celluleactive.getColumn();
var nomws = celluleactive.getSheet().getName();
var n = skillsvector.indexOf(valeur);
so here in "n" I should have the row number in my array corresponding to the value I manually entered on "event". What would be the syntax to define a new array as the nth colum of my iniial array ?
Let me know if I am unclear,
Thanks !
to check if this value is part of my 1st row
You need to define skillsvector as:
var skillsvector = skillsarray[0];
to access the first row of your array
to define a new array as the nth column of my initial array
n returns you the position of the column in your row array
to create a new array containing only cell values of the column n, you have to reduce the 2D value range array with the syntax [row[column]], to a vertical 1D one
One of several ways to do so is mapping
Sample:
var newArray = values.map(function(column){
return column[n];
});
Another possibility is using a loop
Sample:
var newArray = [] ;
for (var i = 0; i < values.length; i++) {
newArray.push(values[i][n]);
}
Thank you very much ziganotschka for your help! Let me post my full code if anyone happens to encounter the same difficulties :
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var wsInfos = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var skillsarray = wsInfosPartners.getRange(1, 1, wsInfos.getLastRow(), wsInfos.getLastColumn()).getValues();
var skillsvector = skillsarray[0];
var nbofskills = skillsvector.length;
function onEdit (e) {
var ActiveCell = e.range;
var val = ActiveCell.getValue();
var row = ActiveCell.getRow();
var col = ActiveCell.getColumn();
var wsname = ActiveCell.getSheet().getName();
var n = skillsvector.indexOf(val);
var skillslist = skillsarray.map(function(column){
return column[n];
});
if (wsname == "Sheet1" && col === 2 && row > 1)
{
var listcell = ws.getRange(row, 3);
ShowSkillsList(skillslist,listcell);
}
}
function ShowSkillsList(skillslist, cell){
var rule = SpreadsheetApp
.newDataValidation()
.requireValueInList(skillslist)
.setAllowInvalid(true)
.build();
cell.setDataValidation(rule);
}
I am trying to copy a column of UI grid elements to an array and sort it and compare the first element of array with the first column data to check the UI grid column data is sorted correctly.
This is my code --
I get the error - unsorted.then is not a function. Can you please help me. also let me know if i can use any other method.
thanks in advance.
var rows = element(by.id('grid2')).element( by.css('.ui-grid-render-container-body')).all( by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index'));
var results = [];
var res = rows.count().then(function(cnt){
console.log('inside loop');
console.log(cnt);
for(i=0; i < cnt; i++){
ele = test.datacell('grid2',i,0);
ele.getText().then(function(txt){
console.log(txt);
results.push(txt);
});
}
var unsorted = results.map(function(element) {
console.log(element.getText());
return element.getText();
});
var sorted = unsorted.then(function(texts) {
return texts.slice(0).sort();
});
ele = cmn.datacell('grid1',0,colcount);
expect(ele.getText()).toEqual(sorted[0]);
for sorting in descending order you could use try this -
var sorted = unsorted.then(function(texts) {
return texts.slice(0).sort(function (a,b) {
return b-a;
});
});
I have an loop Angular JS:
angular.forEach($scope.message, function (item) {
return (item.id_user == input.id_user) ? true : false;
});
How to get index of array element in loop for each item?
I tried:
angular.forEach($scope.message, function (item, $index) {});
Sorry for all the vitriol of the community. You're very close to your solution but are a bit confused by documentation. It's okay, let me help clarify!
In the documentation for angular.forEach you will see the following statement:
Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key, obj), where value is the value of an object property or an array element, key is the object property key or array element index and obj is the obj itself. Specifying a context for the function is optional.
And then the following example:
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
Essentially, the code is like this:
angular.forEach('name of list/array you want to loop through', 'callback function to be called for each element of the list')
The important part that you're missing is that the 'callback...' mentioned above can be handed 3 variables which you can then use in your callback. Your callback will be called for each element in the list. Here is some explanation of those 3 variables:
Value: The value of the i-th element/property in the list/array/object
Key: i - the index belonging to the current item in the array
Object: the the object itself (or array/list itself)
Here is an example i put together for you where I use the Key to create a new string showing the index of each letter in $scope.message. Hope this helped!
angular.forEach($scope.arrayname,function(item,index){
console.log(item,index)
})
There is a way.
var index = 0;
angular.forEach($scope.message, function (item) {
return (item.id_user == input.id_user) ? index : false;
index = index + 1;
});
Here it will return $scope.message index value if item.id_user == input.id_user else returns false. You can also assign $scope.message[index] to some other scope variable like this
var index = 0;
angular.forEach($scope.message, function (item) {
if(item.id_user == input.id_user){
$scope.message[index] = $scope.yourVariable;
}
index = index + 1;
});
var items = ['a','b','c','d','e','f']
angular.forEach(items,function(item,index){
console.log(item)
console.log(index)
}
I have an array of object Contact. Each Contact has 3 arguments:
Id
Name
Function
I'm creating that array in that function:
public ActionResult AutocompleteCollabo(string term)
{
int NumDossier = StructureData.DonneNumDossier((string)Session["NumCRPCEN"], (string)Session["MotDePasse"]);
List<Contact> ListeContacts = StructureData.DonneListeElementDossier(NumDossier);
Contact[] tabContacts = new Contact[ListeContacts.Count()];
int count = 0;
foreach (Contact contact in ListeContacts)
{
tabContacts[count] = contact;
count++;
}
var collaborateurs = tabContacts;
var filteredItems = collaborateurs.Where(
item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
);
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}
Now I would like to compare the string term entered as a parameter in the function to
the name and the function of each object of the array. As the array is a one of objects I can't use indexOf. Does anybody have a solution to do that ?
You can use string.Contains on the Contact object itself since your're using Linq. Assuming both name and function are strings.
var filteredItems = collaborateurs.Where(
item => item.Name.Contains(term) || item.Name.Function.Contains(term)
);
I'm using node js to create a multi player game website. so every time a socket is connected I add that socket in an array like this
var users = [];
var games = [];
var joinKey = [];
var key = 0;
var usersKey = 101;
var gamesKey = 201;
io.sockets.on('connection', function (socket) {
socket.on('connect', function(){
console.log('connect');
var clientId = usersKey;
socket.clientId = clientId;
users[usersKey] = socket;
usersKey++;
socket.emit('getClientId', clientId);
console.log(socket.clientId + ' connected');
console.log('Total users: ' + users.length);
});
here total users shows 102 as user key is 101 and it automatically tales blank values from 0 to 100. this is not normal i guess. also if I retrieve the socket from other array using index, it is undefined if the index is string, like 'g201'
socket.on('createNewGame', function(){
var game = [];
var clientId = socket.clientId;
game[clientId] = socket;
console.log(game);
var gameId = 'g' + gamesKey;
gamesKey++;
games[gameId] = game;
console.log('Total Games: ' + games.length)
socket.gameId = gameId;
var publicKey = ++key;
joinKey[publicKey] = gameId;
socket.emit('gameCreated', publicKey);
});
I'm not getting how to insert and fetch if this is the behavior of array here
To answer your first point:
An array uses numerical indices running from 0.
When you manually place a value in at 101 it will fill the rest of the values in since it has to run from 0, these will be padded with undefined. (as per Andrew Barretts comment)
To answer your second point:
If you need to have an "associate array" or at least what people refer to as an associative array then you should use objects.
game= new Object();
game["g1"]=...
game["g25"]=...
...