Get a random Element from an Array using JavaScript

We can use Math.random , math.floor functions to generate random array items. Length property returns the number of elements in the array. Math.floor() function rounds down a number to the next smallest integer. Math.random() function returns a random number between 0 and 1.  Let’s see the below example

        
const array=[1,2,3,4,5];

const random1 = array[(Math.floor(Math.random() * (array.length)))]
const random2 = array[(Math.floor(Math.random() * (array.length)))]
const random3 = array[(Math.floor(Math.random() * (array.length)))]

console.log(random1, random2, random3)
 
// Output : 2 2 4        
    

Everytime we execute the code then it returns new random value. Let’s see another example

        
const persons = [
  'person1',
  'person2',
  'person3',
  'person4',
  'person5',
  'person6',
  'person7',
  'person8',
  'person9',
  'person10',
] // 10 participants

const winner = persons[Math.floor(Math.random() * persons.length)]
console.log(winner)

// Output : person1        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top