For example: To generate 8 unique random numbers and store them to an array, you can simply do this:
var arr = [];
while(arr.length < 8){
var r = Math.floor(Math.random() * 100) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
Answer from adam0101 on Stack OverflowFor example: To generate 8 unique random numbers and store them to an array, you can simply do this:
var arr = [];
while(arr.length < 8){
var r = Math.floor(Math.random() * 100) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
- Populate an array with the numbers 1 through 100.
- Shuffle it.
- Take the first 8 elements of the resulting array.
Generate unique random numbers in javascript or typescript - Stack Overflow
Generating Unique Random Numbers - JavaScript - SitePoint Forums | Web Development & Design Community
Create a unique number with javascript time - Stack Overflow
javascript - JS function to generate unique random number - Stack Overflow
Videos
» npm install unique-random
There are many examples around internet. You can start with using Math.random()
. For example: generate random number between 1 and 100
Math.floor((Math.random() * 100) + 1);
Just keep in mind that it is not truly random; it is not cryptographically secure. You should probably look into libraries if you need that
Create a function that returns a unique number:
let numbers = [];
const uniqueNumber = (maxVal) => {
const number = Math.floor((Math.random() * maxVal) + 1);
if (!numbers.includes(number)) {
numbers.push(number);
return number;
} else if (numbers.length - 1 !== maxVal) {
uniqueNumber(maxVal);
}
}
const randomNumber = uniqueNumber(100);
console.log(numbers) // returns all unique numbers
This will return a unqiue number between 1 and 100. It also stops at the max length.
The shortest way to create a number that you can be pretty sure will be unique among as many separate instances as you can think of is
Date.now() + Math.random()
If there is a 1 millisecond difference in function call, it is 100% guaranteed to generate a different number. For function calls within the same millisecond you should only start to be worried if you are creating more than a few million numbers within this same millisecond, which is not very probable.
For more on the probability of getting a repeated number within the same millisecond see https://stackoverflow.com/a/28220928/4617597
A better approach would be:
new Date().valueOf();
instead of
new Date().getUTCMilliseconds();
valueOf() is "most likely" a unique number. http://www.w3schools.com/jsref/jsref_valueof_date.asp.
Use the basic Math methods:
Math.random()returns a random number between 0 and 1 (including 0, excluding 1).- Multiply this number by the highest desired number (e.g. 10)
Round this number downward to its nearest integer
Math.floor(Math.random()*10) + 1
Example:
//Example, including customisable intervals [lower_bound, upper_bound)
var limit = 10,
amount = 3,
lower_bound = 1,
upper_bound = 10,
unique_random_numbers = [];
if (amount > limit) limit = amount; //Infinite loop if you want more unique
//Natural numbers than exist in a
// given range
while (unique_random_numbers.length < limit) {
var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
if (unique_random_numbers.indexOf(random_number) == -1) {
// Yay! new random number
unique_random_numbers.push( random_number );
}
}
// unique_random_numbers is an array containing 3 unique numbers in the given range
Math.floor(Math.random() * (limit+1))
Math.random() generates a floating point number between 0 and 1, Math.floor() rounds it down to an integer.
By multiplying it by a number, you effectively make the range 0..number-1. If you wish to generate it in range from num1 to num2, do:
Math.floor(Math.random() * (num2-num1 + 1) + num1)
To generate more numbers, just use a for loop and put results into an array or write them into the document directly.
If the number only needs to be unique on the client side, it's possible. You could create a number based off the current time for example:
var id = new Date().getTime();
However, if this unique ID needs to be unique for every client, as the comments in your OP state, you'll need a server-sided solution:
var id = "<?php echo uniqid() ?>";
First off, to get a random value from the array, you could do this:
var nums = [0,1,2,3,4,5,6,7];
var num = Math.floor(Math.random() * nums.length);
alert(num);
If you needed it to be unique, then it depends on what unique should mean. If you mean that for one user it should never repeat a number until they'd all been exhausted, then you could use a cookie to keep track of which had been shown.
When creating a random number, only use one that isn't yet in your array:
var number = [];
for(i= 0; i <= 5; i++){
var num;
while ( number.includes( num = Math.floor(Math.random()*40) ) );
number[i] = num;
}
console.log(number);
The empty while loop repeatedly selects a number until it finds one that isn't in the number array. Only after that successfully finishes does it then add that number to the array.
random() function generates number randomly so there is a possibility that one number can occur again. To avoid that once a new number is generated by random() function you can check whether this number is already present in your array or not. Add it to your array only if it is not already present. A working snippet is provided below:
function generatenumbers(){
var number = new Array();
var i=0;
while(i<6){
var val = Math.floor(Math.random()*40);
if(number.includes(val) === false){
number.push(val);
i++;
}
}
document.getElementById("generated").innerHTML = "";
i = 0;
for(i=0; i<= number.length - 1; i++){
let node = document.createElement("LI");
let txt = document.createTextNode(number[i]);
node.appendChild(txt);
document.getElementById("generated").appendChild(node);
}
}