get a random element from an array in javascript

You can get a random element from an array in JavaScript using the Math.random() method and array indexing. Here's an example:

index.tsx
let array = [1, 2, 3, 4, 5];

let randomElement = array[Math.floor(Math.random() * array.length)];

console.log(randomElement); // Outputs a random element from the array
171 chars
6 lines

In the code above, Math.random() generates a random decimal number between 0 and 1. We multiply this number by the length of the array to get a random index within the range of the array. We use Math.floor() to round down the resulting decimal number to the nearest integer, which ensures that the index is within the bounds of the array.

Finally, we use the random index to access a random element from the array and assign it to randomElement.

gistlibby LogSnag