Open In App

How to select a random element from array in JavaScript ?

In this article, 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.

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

These are the following approaches for solving this problem:



Using Math.random() function

Example: This example implements the above approach.  






let arr = ["GFG_1", "GeeksForGeeks",
    "Geeks", "Computer Science Portal"];
 
function GFG_Fun() {
    console.log(arr[(Math.floor(Math.random() * arr.length))]);
}
GFG_Fun()

Output
Computer Science Portal

Using custom function

Example: This example implements the above approach. 




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
Geeks

Using Lodash _.sample method

Example: This example implements the above approach. 




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array1 = ([3, 6, 9, 12]);
 
// Use of _.sample() method
let gfg = _.sample(array1);
 
// Printing original Array
console.log("original array1: ", array1)
 
// Printing the output
console.log(gfg);

Output:

original array1: [ 3, 6, 9, 12 ]
12

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.


Article Tags :