How to use custom function In Javascript
- 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 array length).
- Subtract 1 to get the index ranging from(0 to arrayLength-1).
Example: This example implements the above approach.
let arr = ["GFG_1", "w3wiki",
"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
w3wiki
How to select a random element from array in JavaScript ?
We are going to learn how can we select a random element from an array in JavaScript. we will be given an array and we need to print a random element from that array.
Selecting a random element from an array is a common task, especially in scenarios where you need to introduce randomness or unpredictability into your code. Whether you’re building a game, conducting statistical analysis, or implementing a feature that requires random selection, knowing how to pick a random element from an array is important.
These are the following approaches for solving this problem:
Table of Content
- Using Math.random() function
- Using custom function
- Using Lodash _.sample method
- Using Array.splice() with Math.random()
- Using Array destructuring and Math.floor()