I am trying that I need to generate a random number between 100-1000 and record database it but every number must be unique from others. how can I do it in Meteor, Thank you.
Asked
Active
Viewed 1,377 times
0
-
This is JavaScript, not necessarily Meteor. – fuzzybabybunny Jul 07 '15 at 09:11
1 Answers
1
You can follow this logic:
var arr = [];
for (var i = 100; i <= 1000; i++) {
arr.push(i);
}
Or, if Underscore is available:
var arr = _.range(100, 1001);
Now we have an array including all the unique values you want to be assigned. Then for generation:
var rand = Math.floor((Math.random()*arr.length));
var randNumber = arr[rand];
arr.splice(rand,1);
There you go, you have a random number between 100 and 1000 called randNumber
, and cannot get the same one next time you run that bit of code.
But you will need to store a big arr
array somewhere as long as you want to generate random numbers. It really depends on how persistant you want this array to be, if the process needs to take place in a long period of time (for example "each time a user does X") or if it is a one-time process.