How to get Random Elements from an Array in JavaScript

Sometimes we need to get a random element from an array in JavaScript. An array is a list of indexed elements so in order to get a random element, we need to pick one of the indexes at random.

 

Getting a Random Index Number

Array indexes start at 0 and count up until the final element. Therefore we need to pick a random number between 0 and the length of the array minus 1. We can do this multiplying the output of Math.random() by the length of the array and rounding that down to a whole number using Math.floor().

 

var fruits = ['apple', 'strawberry', 'orange', 'apricot'];

var rand_index = Math.floor(Math.random() * fruits.length);

console.log(rand_index);
3

 

Learn more about how the Math.random() function works.

 

Accessing the value

To access the randomly picked index we can pass the number inside [] (square brackets) on the array variable.

 

var rand_val = fruits[rand_index];

console.log(rand_val);
apricot

 

Conclusion

You now know how to get random elements from an array in JavaScript.

array index random number