How to select a random element from array in JavaScript ?
In this article, the task is to select a random element from the array using JavaScript. We can do this by using the Math.random() method of Javascript.
Approach 1:
- Use Math.random() function to get the random number between(0-1, 1 exclusive).
- Multiply it by the array length to get the numbers between(0-arrayLength).
- Use Math.floor() to get the index ranging from(0 to arrayLength-1).
Example: This example implements the above approach.
Javascript
let arr = ["GFG_1", "GeeksForGeeks", "Geeks", "Computer Science Portal"];function GFG_Fun() { console.log(arr[(Math.floor(Math.random() * arr.length))]);}GFG_Fun() |
Output
GeeksForGeeks
Approach 2:
- The random(a, b) method is used to generate a number between(a to b, b exclusive).
- Taking the floor value to range the numbers from (1 to arrayLength).
- Subtract 1 to get the index ranging from(0 to arrayLength-1).
Example: This example implements the above approach.
Javascript
let arr = ["GFG_1", "GeeksForGeeks", "Geeks", "Computer Science Portal"];function random(mn, mx) { return Math.random() * (mx - mn) + mn;}function GFG_Fun() { console.log(arr[(Math.floor(random(1, 5))) - 1]);}GFG_Fun() |
Output
GFG_1
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


Please Login to comment...