You can pick a random element from an array in the following steps:
- Generate a random number between
0and1usingMath.random(); - Multiply the random number with
array.length(to get a number between0andarray.length); - Use
Math.floor()on the result to get an index between0andarray.length - 1; - Use the random index on the array to get an element at random.
For example, let's suppose you have an array of colors like the following from which you wish to pick a color randomly:
const colors = [ 'blue', 'yellow', 'orange', 'red' ];
const randIndex = Math.floor(Math.random() * colors.length);
console.log(colors[randIndex]);