how to choose a random name from a list in javascript


        //To choose a random name from a list in JavaScript, you can follow the below steps:
        
        //Step 1: Create an array with the list of names.
        var namesList = ["John", "Mary", "David", "Linda", "Sarah", "James", "Jennifer"];
        
        //Step 2: Use the Math.floor() and Math.random() functions to generate a random index from the array
        var randomIndex = Math.floor(Math.random() * namesList.length);
        
        //Step 3: Use the random index to access a random name from the list
        var randomName = namesList[randomIndex];
        
        //Step 4: Print the random name on the console or any other place as per your requirement.
        console.log("Random Name: "+randomName);
    

Above code will work for very small arrays with less than 1000 elements, but if you are working with larger arrays then consider using a more optimized and efficient algorithm. One such algorithm is Fisher-Yates shuffle. It's important to note that this algorithm modifies the original array. Here's how you can implement Fisher-Yates shuffle in JavaScript:


        // Step 1: Create an array with the list of names.
        var namesList = ["John", "Mary", "David", "Linda", "Sarah", "James", "Jennifer"];

        // Step 2: Implement the Fisher-Yates shuffle algorithm
        function shuffle(array) {
            var currentIndex = array.length;
            var temporaryValue, randomIndex;

            while (currentIndex !== 0) {
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex -= 1;
                temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
                array[randomIndex] = temporaryValue;
            }

            return array;
        }

        // Step 3: Call the shuffle function on your namesList
        var shuffledList = shuffle(namesList);

        // Step 4: Access a random name from the shuffled list
        var randomName = shuffledList[0];

        // Step 5: Print the random name on the console or any other place as per your requirement.
        console.log("Random Name: "+randomName);
    

Hope this helps!

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