print random string from an array to screen in javascript

Introduction

Arrays are an important part of JavaScript and are commonly used to store multiple values in a single variable. One of the common operations performed on an array is to access its elements randomly. In this article, we will discuss how to print a random string from an array to the screen in JavaScript.

Method 1: Using Math.random() method

The easiest way to print a random string from an array is by using the Math.random() method in JavaScript. This method generates a random number between 0 and 1. We can use this number to access a random element from the array by multiplying it with the length of the array and taking the floor of the result.


var myArray = ['apple', 'orange', 'banana', 'grape', 'watermelon'];
var randomIndex = Math.floor(Math.random() * myArray.length);
document.getElementById('output').innerHTML = myArray[randomIndex];

In the above code, we have declared an array of fruits and used the Math.random() method to generate a random index between 0 and the length of the array. We then accessed the element at that index using bracket notation and printed it to the screen using the innerHTML property of the document object.

Method 2: Using Shuffle Algorithm

Another way to print a random string from an array is by using a shuffle algorithm. A shuffle algorithm is a method that randomly rearranges the elements of an array. We can then access the first element of the shuffled array to get a random string.


function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    while (0 !== currentIndex) {

        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

var myArray = ['apple', 'orange', 'banana', 'grape', 'watermelon'];
var shuffledArray = shuffle(myArray);
document.getElementById('output').innerHTML = shuffledArray[0];

In the above code, we have defined a shuffle function that takes an array as input and returns a shuffled array. This function uses a while loop to iterate over the array and for each element, it generates a random index and swaps it with the current index. We then declared an array of fruits and passed it to the shuffle function to get a shuffled array. Finally, we accessed the first element of the shuffled array and printed it to the screen using the innerHTML property of the document object.

Conclusion

Printing a random string from an array in JavaScript can be done in multiple ways. The two methods discussed above are easy to understand and implement. You can choose the method that suits your needs and use it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe