Want to store random numbers in Array

Vishal40
Tera Contributor

Hello Developers,

On button click ( UI action ) I am trying to generate random numbers between 1 to 100.

I want to store all generated random numbers on the form text field with comma-separated values.

Please help me with how I can do the same.

function selectNumber()
{
var finalArr = [];
var answer = confirm("Are you sure to fill the information");
if (answer==true)
{
var n= 100; // Outbound Limit
var x = Math.floor(Math.random() * n); //Generates random number from 0-n
var num = Number(x);
alert(num);
}

}

 

 

1 ACCEPTED SOLUTION

Try this script. This should fix

function selectNumber() {
{
var n = 5; // Outbound Limit
var x = Math.floor(Math.random() * n); //Generates random number from 0-n
var num = Number(x).toString();
var currentVal = g_form.getValue("u_crossed_number");
var currentArr = currentVal.split(",");
// Reset if the count is greater than Outbound limit
if(currentArr.length >= n || currentArr == "")
currentArr = [];

// Repeat the while loop until the script didn't find the existing number
while (currentArr.indexOf(num) >= 0) {
x = Math.floor(Math.random() * n);
num = Number(x).toString();
}
currentArr.push(num);
g_form.setValue("u_crossed_number",currentArr.join(","));

}

Thank you,
Palani

View solution in original post

20 REPLIES 20

Gunjan Kiratkar
Kilo Patron
Kilo Patron

Hi @Vishal ,

 

How many random numbers do you want to generate from 1-100?

Is it fixed or not?

 

Regards,

Gunjan Kiratkar

Consultant - ServiceNow, Cloudaction

Rising Star 2022


Please Mark My Response as Correct/Helpful based on Impact
Regards,
Gunjan Kiratkar
2X ServiceNow MVP
Community Rising Star 2022
Youtube : ServiceNow Guy

If it is 100 then you can test the below code:  

 

function selectNumber()

{

var answer = confirm("Are you sure to fill the information");

if (answer==true)

{

var randomNum=[];

var n= 100; // Outbound Limit

for(var i=0;i<n;i++){

var x = Math.floor(Math.random() * n); //Generates random number from 0-n

randomNum.push(Number(x));

}

return randomNum;

}

}    
 
 

Please mark my answer as helpful/correct if it resolves your query.

Regards,

Gunjan Kiratkar

Consultant - ServiceNow, Cloudaction

Rising Star 2022

Please Mark My Response as Correct/Helpful based on Impact
Regards,
Gunjan Kiratkar
2X ServiceNow MVP
Community Rising Star 2022
Youtube : ServiceNow Guy

Random numbers are generated but whatever random numbers are generating I want to save all those in the text field with comma separation.

The above script has output same as per your requirement:-

find_real_file.png

Regards,

Gunjan Kiratkar

Consultant - ServiceNow, Cloudaction

Rising Star 2022


Please Mark My Response as Correct/Helpful based on Impact
Regards,
Gunjan Kiratkar
2X ServiceNow MVP
Community Rising Star 2022
Youtube : ServiceNow Guy