Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Select a Random Element from Array in JavaScript?
To select a random element from array in JavaScript, means getting any random element from the given array. We will understand various approaches for selecting a random element from array.
In this article, we are having an array and our task is to select a random element from array in JavaScript
Approaches to Select a Random Element from Array
Here are the most effective approaches to select a random element from array in JavaScript which we will be discussing in this article with stepwise explanation and complete example codes.
- Using Math.random() Method
- Using Lodash _.sample() Method
- Using getMilliseconds() Method
- Using Fisher-Yates Shuffle Algorithm
Using Math.random() Method (Recommended)
The most common and reliable approach is using Math.random() with Math.floor() method. This combination generates a random index within the array bounds.
How It Works
- Math.random() generates a decimal number between 0 (inclusive) and 1 (exclusive)
- Multiply by array length to get a decimal between 0 and array.length
- Math.floor() rounds down to get a valid array index
- Use this index to access the random element
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Random Element from Array - Math.random()</title>
</head>
<body>
<h2>Select Random Element using Math.random()</h2>
<p>Click the button to select a random element from the array.</p>
<button onclick="selectRandom()">Select Random Element</button>
<br><br>
<div id="array"></div>
<div id="result"></div>
<script>
const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
document.getElementById("array").innerHTML = "Array: [" + fruits.join(', ') + "]";
function selectRandom() {
const randomIndex = Math.floor(Math.random() * fruits.length);
const randomElement = fruits[randomIndex];
document.getElementById("result").innerHTML =
"Random element: " + randomElement + " (Index: " + randomIndex + ")";
}
</script>
</body>
</html>
Using Lodash _.sample() Method
For projects already using Lodash library, the _.sample() method provides a clean, one-line solution.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Random Element - Lodash Sample</title>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
</head>
<body>
<h2>Select Random Element using Lodash _.sample()</h2>
<button onclick="selectRandom()">Select Random Element</button>
<br><br>
<div id="array"></div>
<div id="result"></div>
<script>
const colors = ['Red', 'Blue', 'Green', 'Yellow', 'Purple'];
document.getElementById("array").innerHTML = "Array: [" + colors.join(', ') + "]";
function selectRandom() {
const randomElement = _.sample(colors);
document.getElementById("result").innerHTML = "Random element: " + randomElement;
}
</script>
</body>
</html>
Using getMilliseconds() Method
This approach uses the current time's millisecond value as a source of randomness. While creative, it's less random than Math.random().
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Random Element - getMilliseconds()</title>
</head>
<body>
<h2>Select Random Element using getMilliseconds()</h2>
<p>This method uses current time milliseconds for randomness.</p>
<button onclick="selectRandom()">Select Random Element</button>
<br><br>
<div id="array"></div>
<div id="result"></div>
<script>
const numbers = [10, 20, 30, 40, 50, 60, 70];
document.getElementById("array").innerHTML = "Array: [" + numbers.join(', ') + "]";
function selectRandom() {
const randomIndex = new Date().getMilliseconds() % numbers.length;
const randomElement = numbers[randomIndex];
document.getElementById("result").innerHTML =
"Random element: " + randomElement + " (Index: " + randomIndex + ")";
}
</script>
</body>
</html>
Using Fisher-Yates Shuffle Algorithm
This approach shuffles the entire array using the Fisher-Yates algorithm and returns the first element. It's overkill for selecting one element but useful when you need multiple random elements.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Random Element - Fisher-Yates Shuffle</title>
</head>
<body>
<h2>Select Random Element using Fisher-Yates Shuffle</h2>
<p>This shuffles the array and returns the first element.</p>
<button onclick="selectRandom()">Select Random Element</button>
<br><br>
<div id="array"></div>
<div id="shuffled"></div>
<div id="result"></div>
<script>
const originalArray = ['A', 'B', 'C', 'D', 'E'];
document.getElementById("array").innerHTML = "Original Array: [" + originalArray.join(', ') + "]";
function fisherYatesShuffle(array) {
const shuffled = [...array]; // Create a copy to avoid modifying original
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
function selectRandom() {
const shuffledArray = fisherYatesShuffle(originalArray);
document.getElementById("shuffled").innerHTML =
"Shuffled Array: [" + shuffledArray.join(', ') + "]";
document.getElementById("result").innerHTML =
"Random element: " + shuffledArray[0];
}
</script>
</body>
</html>
Comparison of Methods
| Method | Complexity | Performance | Best Use Case |
|---|---|---|---|
| Math.random() | Simple | Fastest | General purpose (Recommended) |
| Lodash _.sample() | Simple | Fast | Projects using Lodash |
| getMilliseconds() | Simple | Fast | Educational purposes |
| Fisher-Yates | Complex | Slower | Multiple random elements needed |
Conclusion
The Math.random() with Math.floor() method is the most practical and widely-used approach for selecting random elements from arrays. It's simple, efficient, and doesn't require external libraries, making it the recommended solution for most JavaScript applications.
