JavaScript - Select a Random Element from JS Array
Selecting a random element from array in JavaScript is done by accessing an element using random index from the array. We can select the random element using the Math.random() function.

1. Using Math.random() Method
The Math.random() method is used to get the random number between 0 to 1 (1 exclusive). It can be multiplied with the size of the array to get a random index and access the respective element using their index.
let a = [10, 20, 30, 40, 50];
let i = Math.floor(Math.random() * a.length);
let r = a[i];
console.log(r);
Output
50
2. Using Fisher-Yates Shuffle Algorithm
The Fisher-Yates Shuffle Algorithm, also known as the Knuth Shuffle is a method for randomly shuffling elements in an array. It works by iterating over the array from the last element to the first, swapping each element with a randomly chosen one that comes before it (including itself). This ensures that each possible permutation of the array elements is equally likely, making it highly effective for unbiased randomization. The algorithm is efficient with a time complexity of O(n), where n is the number of elements in the array.
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
let a = [10, 20, 30, 40, 50];
shuffleArray(a);
let r = a[0];
console.log(r);
Output
30