Open In App

How to select a random element from array in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

select-random-elements-from-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

  • Use the “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 the “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

Computer Science Portal

Using custom function

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

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

Geeks

Using Lodash _.sample method

  • In this approach we are using the third party librray.
  • The _.sample() method takes an array as an input an returns the random element from that given array.
  • we willuse _.sample() method to print random element from an array.

Example: This example implements the above approach. 

Javascript




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



Last Updated : 30 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads