# 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

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

Previous
Next