Open In App

JavaScript - Select a Random Element from JS Array

Last Updated : 28 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

select-random-elements-from-array
How to select a random element from an array in JavaScript?

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.

JavaScript
let a = [10, 20, 30, 40, 50];
let i = Math.floor(Math.random() * a.length);
let r = a[i];
console.log(r);

Output
30

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).

JavaScript
function shuffleA(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
}

let a = [10, 20, 30, 40, 50];

shuffleA(a);

let r = a[0];
console.log(r);

Output
30

3. Using Array.prototype.sort()

This method randomly shuffles the array using the sort() function with a random comparison, and then picks the first element. While it works, it can be inefficient for large arrays as it sorts the entire array.

JavaScript
let colors = ["red", "green", "blue", "yellow"];
let random = colors.sort(() => 0.5 - Math.random())[0];
console.log(random);

Output

blue

In this example

  • The sort() function is called with a random comparison function (() => 0.5 - Math.random()).
  • This shuffles the array randomly.
  • The first element of the shuffled array is selected.

Note: This method modifies the original array by shuffling it.

4. Using Array.prototype.slice()

slice() can be used to create a sub-array and select a random element. This method is typically used for copying or extracting elements from an array.

JavaScript
let n = [10, 20, 30, 40];
let random = n.slice(Math.floor(Math.random() * n.length), Math.floor(Math.random() * n.length) + 1)[0];
console.log(random);

Output
20

In this example

  • slice() extracts a portion of the array starting from a random index.
  • The [0] selects the first element of the sliced array.

Note: This method creates a new array with one element, which may not be the most efficient for large arrays.condition.


Similar Reads