-1

I have an scenario to generate random numbers that should generate from the given numbers.

for example, I have an array num=[23,56,12,22]. so i have to get random number from the array

vicky
  • 5
  • 1
  • 4

5 Answers5

2

You can do something like this:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

let num=[23,56,12,22];
let randomPosition = getRandomInt(num.length);
console.log(num[randomPosition])
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
1

You can make a function that returns a random integer between 0 and the length of the array, like this:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

Then call it, like this:

let randomInt = getRandonInt(lengthOfArray);

console.log(randomInt);

Expected output: 0, 1, 2 .. length of array

Then just simply use the randomInt to get whatever you need from your array entries.

garff
  • 41
  • 3
1

you can generate a random index between 0 and array.length - 1

function getRandomInt(max) {
    return Math.floor(Math.random() * Math.floor(max));
}

function getRandomIntFromArray(array) {
    return array[getRandomInt(array.length)]
}

const num = [23,56,12,22]

getRandomIntFromArray(num)
0xChqrles
  • 433
  • 1
  • 5
  • 10
1

Use Math.floor(Math.random() * x), where x is the length of the Array to generate a random number between 0 and the max index

const data = [23,56,12,22]

function randomIndex (array) {
  return array[Math.floor(Math.random() * array.length)];
}

console.log(randomIndex(data));
Shiny
  • 4,945
  • 3
  • 17
  • 33
0

How about drawing a uniform distributed random integer in the interval [0,len(num)-1] which represents the index of the number you draw from your array num.

This is a very simple and straight forward approach.

Tinu
  • 2,432
  • 2
  • 8
  • 20