Generate three random names from an array and assign them to an element

This website is amazing! I've interacted with so many awesome people here!

Currently, I have successfully implemented code to get one random name from an array. However, I now want to display three different names each time, and I'm facing a roadblock.

Is there anyone out there who can help me out and showcase their expertise? I would greatly appreciate it! <3

The JavaScript Code

     <script> 

window.onload = funkytown;

function funkytown() {
    document.getElementById("btn").onclick = name;
}

function name() {

        var students = ["Mike","Nick","Slagathor","Banana","Rick","Astley","Rock","JW","pronax"];
        var randomize = students.splice(Math.floor(Math.random() * students.length), 1);

        var html = "Random names: ";

        document.getElementById("text").innerHTML = html + randomize;


     }
     </script>

The HTML Structure

<span id="text"></span>
<input type="button" id="btn" value="Randomize!" />

Answer №1

If you have a function that can provide you with a random name from an array, you can utilize it recursively to gather three unique names.

 var randomNames=[]; 
 var count=0;

function name() {
    if(count==3){
      return;
    }
    var students = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"];
    var randomize = students.splice(Math.floor(Math.random() * students.length), 1);
    if(randomNames.indexOf(randomize) == -1){
        randomNames.push(randomize );
        ++count;
    }
    name();
  }

 var html = "Random names: ";

 document.getElementById("text").innerHTML = html + randomNames;

Answer №2

function groovyVille() {
    document.getElementById("btn").onclick = displayNames;
}

function displayNames() {
    var randomizedNames = [],
        students = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"];

    for (var i = 0; i < 3; i++) {
        randomizedNames.push(students.splice(Math.floor(Math.random() * students.length), 1));
    }

    var outputText = "Tilfeldige navn: ";

    document.getElementById("text").innerHTML = outputText + randomizedNames.join(", ");
}

groovyVille();

Output: Tilfeldige navn: Line, Per, Ole

Check out this jsfiddle demo

Answer №3

There are numerous ways to tackle this problem

using a for loop

function generateNames() {
    var students = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"];
    var randomize = [];
    for(var i = 0; i < 3; i++) {
        randomize.push(students.splice(Math.floor(Math.random() * students.length), 1));
    }
    var output = "Random names: ";
    document.getElementById("text").innerHTML = output + randomize.join(' ');
}

a slightly unconventional method with array.map

function generateNames() {
    var students = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"];
    var randomize = [1,2,3].map(function() {
        return students.splice(Math.floor(Math.random() * students.length), 1);
    }).join(' ');
    var output = "Random names: ";
    document.getElementById("text").innerHTML = output + randomize;
}

eliminate random elements until only 3 are left

function generateNames() {
    var students = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"];
    while(students.length > 3) {
        students.splice(Math.floor(Math.random() * students.length), 1);
    }
    var output = "Random names: ";
    document.getElementById("text").innerHTML = output + students.join(' ');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the value of the second child element in a table cell when clicking on it with Javascript

I have created a table with one row that includes the title of the month and a cell containing an inner table with multiple rows and cells. I want to display the content of the second cell in the second table as a modal box or alert dialog when it is click ...

Mastering the art of implementing async/await properly within token validation scenarios

I am currently working on setting up an Express.js backend for a website that authenticates users using Google Sign-in. My goal is to develop a RESTful API call that: Accepts an ID token. Authenticates the token using Google's OAuth2 Library. Veri ...

Implementing a click event on header elements within a full calendar component in a React application

I'm currently integrating full calendar into my project. I need to implement click events on the header buttons such as prev, next, today, and others. This is how I've set up full calendar with the specified header buttons: <FullCalendar d ...

instructions on invoking a function within the knockout $.getJSON() operation

I am currently experimenting with a basic knockout script (still in the learning process). $.getJSON(clientUrl + "/list/" + 1, function (data) { var viewModel = { clients: ko.observableArray(data) }; ko.applyBindings(viewModel); }); The initial arg ...

AngularJS dropdown with multiple selections within a Bootstrap modal

Being new to AngularJS, I apologize for asking this question in advance. I am utilizing Angular bootstrap modal from the following link: https://angular-ui.github.io/bootstrap/ and multiple select dropdown list from: https://codepen.io/long2know/pen/PqLR ...

"Upon clicking the login button, I encountered an issue with redirecting to the destination

I've been working on developing a login page using Angular framework. However, I'm facing an issue where I am unable to access the destination page after entering the login credentials. Below, you can find a snippet of the code from the login.com ...

What methods can I use to enable web browsers to remember form field data that is not transmitted in the usual manner?

The code provided here is almost perfect in terms of functionality. function post_form() { http=new XMLHttpRequest(); http.onreadystatechange=function() { if (http.readyState==4 && http.status==200) some_div.innerHTML=http.responseText; ...

Removing duplicate entries from a dropdown menu can be achieved by implementing

As a newcomer to the world of PHP PDO, I've learned that the database connection should be in a separate PHP file. However, after spending an entire day trying different things, I'm still facing issues. I suspect that the duplicate entries are a ...

Encountering difficulty importing a class into the index.js file

225/5000 Hello, I seem to be facing a bit of trouble despite my efforts in trying to import a class into my index.js file. Here is what my index.js file looks like: import {Brandade} from "./modules/Brandade"; const brandade = new Brandade(&ap ...

Enhance a path SVG component with properties for a map in a React application

My goal is to develop a strategy game using an SVG map that I have created. I want to include attributes such as "troops" in each "path" representing territories, along with other properties. Can I add these attributes to individual paths and then use this ...

Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads. Un ...

Using jQuery UI datepicker - how to set a parameter based on a specific condition

New to the world of JavaScript, I am trying my hand at implementing the jQuery UI datepicker widget. My goal is to add an additional line to the widget parameters if the variable selectedDate has a value. However, my current approach seems to be ineffecti ...

The `getScript` function in jQuery is not working as expected, even though the path is accurate and the script was successfully downloaded

Recently, I created a website using Mustache.js and incorporated templates loaded via AJAX with jQuery. During the testing phase on my local environment, everything worked perfectly. However, upon uploading the site to my school server, an issue arose whe ...

Enhancing Redux efficiency with substantial data structures

I have developed a web application using Redux and React. It is an analytics application that displays a significant amount of data. However, I am facing performance issues as the size of my data store increases. What is the best approach to prevent perfo ...

Difficulty encountered with fetching results using jQuery autocomplete with AJAX as the data source

My autocomplete feature is not working properly with my ajax data source. Here is my code: $("#id_q").autocomplete({ source: function (request, response) { $.ajax({ url: "/search/autocomplete/", dataType: "jsonp", ...

`Where can I locate a grid example?`

Right here: Upon reading the documentation, I discovered: onItemInserting has the following arguments: { grid // represents the grid instance item // item being inserted } In my software application there are multi ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...

Identifying Labels in ThreeJS

I have a simple Threejs code where I am experimenting with click events using Raycaster. By using the BOX geometry, I have created three cubes in my scene. Additionally, I have utilized CSS2DRenderer.js to add a label above one of the cubes. My goal is t ...

How can I show the remaining paragraph text upon clicking a button in a responsive manner using CSS and JavaScript?

I want to add a nice animation effect to the height of my text when a button is clicked. I've managed to achieve this by setting a height: 30px with overflow: hidden initially, and then toggling a class with height: 300px. However, I'm facing an ...

Utilizing the Chinese Remainder Theorem within JavaScript Programming

Attempting to tackle the challenge presented in part 2 of Advent of Code 2020 day 13, I came across discussions referencing the intriguing concept known as the Chinese Remainder Theorem. Various approaches were explored, including utilizing an older implem ...