Select a Random Element from Array in JavaScript



To select a random element from array in Javascript, means getting any random element from the given array. We will understand various approaches for selecting a random element from array.

In this article, we are having an array and our task is to select a random element from array in JavaScript

Approaches to select a random element from array

Here is a list of approaches to select a random element from array in JavaScript which we will be discussing in this article with stepwise explaination and complete example codes.

Using Math.random() Method

To select a random element from array in JavaScript, we have used Math.random() with Math.floor() method which picks a random number and rounds down to nearest whole number.

  • We have used a button Select which triggers the function randomElement() upon clicking over it.
  • We have used two div elements to display array and result i.e random element from array.
  • The Math.random() picks a random number between 0 - 1. Then we multiply this random number with array length to get the index of array between 0 - 5.
  • The Math.floor() method rounds down the number to nearest whole number. We get a random index which is then passed into arr[] to get the element at that index.
  • This random element is stored in rndmEle which is displayed using getElementById() method and innerHTML property.

Example

Here is a complete example code implementing above mentioned steps to select a random element from array in JavaScript using Math.random() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Selecting a Random Element from Array in JavaScript
    </title>
</head>
<body>
    <h2>
        Selecting a Random Element from Array in JavaScript
    </h2>
    <p>
        In this example, we have used <strong>Math.random()</strong>
        and <strong>Math.floor()</strong> method to select a random 
        element from array in JavaScript.
    </p>
    <button onclick="randomElement()">Select</button>
    <br><br>
    <div id="array"></div>
    <div id="result"></div>
    <script>
        const arr = [1, 2, 3, 4, 5];
        document.getElementById("array").innerHTML = "Array: " + arr;
        function randomElement() {
            const rndmEle = arr[Math.floor(Math.random() * arr.length)];
            document.getElementById("result")
                .innerHTML = "Random element from array: " + rndmEle;
        }
    </script>
</body>
</html>

Using Lodash _.sample() Method

In this approach we have used Lodash library to select a random element from array. We have used _.sample() method of Lodash library to select a random element from array.

  • We have used script tag in head section to include the Lodash library from a Content Delivery Network (CDN) to add Lodash's utility functions which allows us to use lodash methods such as _.sample().
  • We have used a button Select which triggers the function randomElement() upon clicking over it.
  • We have used two div elements to display array and result i.e random element from array.
  • Then, we have used _.sample() method which picks a random element from the array.
  • This random element is stored in rndmEle which is displayed using getElementById() method and innerHTML property.

Example

Here is a complete example code implementing above mentioned steps to select a random element from array in JavaScript using Lodash _.sample() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Selecting a Random Element from Array in JavaScript
    </title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
</head>
<body>
    <h2>
        Selecting a Random Element from Array in JavaScript
    </h2>
    <p>
        In this example, we have used <strong>Lodash _.sample()
        </strong> method to select a random element from array
        in JavaScript.
    </p>
    <button onclick="randomElement()">Select</button>
    <br><br>
    <div id="array"></div>
    <div id="result"></div>
    <script>
        const arr = [1, 2, 3, 4, 5];
        document.getElementById("array").innerHTML = "Array: " + arr;
        function randomElement() {
            const rndmEle = _.sample(arr);
            document.getElementById("result")
                .innerHTML = "Random element from array: " + rndmEle;
        }
    </script>
</body>
</html>

Using getMilliseconds() Method

In this approach to select a random element from array we have used getMilliseconds() method of Date() object which returns the milliseconds in the specified date according to local time.

  • We have used a button Select which triggers the function randomElement() upon clicking over it.
  • We have used two div elements to display array and result i.e random element from array.
  • We have used new Date().getMilliseconds() to get the millisecond value of current date and time.
  • Then we have applied modulo operator to retrieved millisecond value with array length to get the index in range of 0 - arr.length-1. This index is then passed to array arr[] to get the element.
  • This random element is stored in rndmEle which is displayed using getElementById() method and innerHTML property.

Example

Here is a complete example code implementing above mentioned steps to select a random element from array in JavaScript using getMilliseconds() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Selecting a Random Element from Array in JavaScript
    </title>
</head>
<body>
    <h2>
        Selecting a Random Element from Array in JavaScript
    </h2>
    <p>
        In this example, we have used <strong>getMilliseconds()</strong>
        method of <strong>Date()</strong> object to select a random 
        element from array in JavaScript.
    </p>
    <button onclick="randomElement()">Select</button>
    <br><br>
    <div id="array"></div>
    <div id="result"></div>
    <script>
        const arr = [1, 2, 3, 4, 5];
        document.getElementById("array").innerHTML = "Array: " + arr;
        function randomElement() {
            const rndmIndex = new Date().getMilliseconds() % arr.length;
            const rndmEle = arr[rndmIndex];
            document.getElementById("result")
                .innerHTML = "Random element from array: " + rndmEle;
        }
    </script>
</body>
</html>

Using Fisher-Yates Shuffle Algorithm

In this approach we have used Fisher-Yates Shuffle Algorithm to select a random element from array.

  • We have used a button Select which triggers the function randomElement() upon clicking over it.
  • We have used two div elements to display array and result i.e random element from array.
  • Then we have used for loop to iterate tha array from last element to starting element swapping each element with a randomly genetated element using Math.floor() and >Math.random().
  • The process is repeated till i index reaches 1.

Example

Here is a complete example code implementing above mentioned steps to select a random element from array in JavaScript using Fisher-Yates Shuffle algorithm.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Selecting a Random Element from Array in JavaScript
    </title>
</head>
<body>
    <h2>
        Selecting a Random Element from Array in JavaScript
    </h2>
    <p>
        In this example, we have used the <strong>Fisher-Yates Shuffle</strong>
        algorithm to shuffle the array and then select a random element from it.
    </p>
    <button onclick="randomElement()">Select</button>
    <br><br>
    <div id="array"></div>
    <div id="result"></div>
    <script>
        const arr = [1, 2, 3, 4, 5];
        document.getElementById("array").innerHTML = "Array: " + arr;
        function fisherYatesShuffle(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
        }
        function randomElement() {
            fisherYatesShuffle(arr);  
            document.getElementById("result")
                .innerHTML = "Random element from shuffled array: " + arr[0];
        }
    </script>
</body>
</html>

Conclusion

In this example, we discussed how to select a random element from array in Javascript using various approaches. We have used following approaches: Math.random() with Math.floor(), Lodash _.sample() method, getMilliseconds() method and Fisher-Yates Shuffle Algorithm.

Updated on: 2024-11-20T14:39:51+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements