Creating Randomized Arrays in Javascript

Hey there! I'm currently working on a school project where I need to create random groups of names from a given list. The size and number of groups will depend on the user's input. I've managed to write code that randomly selects an element from the array, but now I need some assistance with grouping the names together. Here's what I have so far, but it's not fully functional. Any help would be greatly appreciated. Thank you!

function generateRandomName()
        {
        var names = prompt("Enter your names").split(",")
        console.log(names);
        var random = names[Math.floor(Math.random() * names.length)];
         document.getElementById("h2").innerHTML = random;
        }
       

 function groupNames()
       {  
            var names = prompt("Enter your names").split(",");
            var random = names[Math.floor(Math.random() * names.length)];
            var numElements = document.getElementById("input2").value;
            for (i=0;i <= names.length; i++)
            {   
                
                  

                var newNameGroup = [random];
                console.log(newNameGroup);
               //print name to a new list
                //remove name from old list
                /* var arr = prompt("Enter your names").split(",")
                var groupNum = document.getElementById("input1").value;
                var newArrays =  arr.length / groupNum; */
                

            }

        
       } 
  /* Reset */
  * {
  margin: 0;
  padding: 0;
  }

  html,body {
    height:100%;
    margin:0;
    font-family: 'Montserrat', 'sans-serif';
    color:#424242;
    overflow: hidden;
  }
  .display {
    text-align: center;
    display: table;
    height:100%;
    margin:0 auto;
  }
  .wrap {
    display: table-cell;
    vertical-align: middle;
  }
  p {
    font-size: 50px; /* For lamers who don't support viewport sizing */
    font-size:20vmin;
    text-align: center;
    margin: 0;
  }
#h2 {
    float: center;
    font-size: 30vmin;

    background-size: contain;

}
  input.text-display {
    display: inline-block;
    color: #5E5E5E;
    font: bold 20px arial;
    text-decoration: none;
    text-align: center;
    margin: 20px auto;
    padding: 15px 20px;
    background: #EFF0F2;
    border-radius: 4px;
    border-top: 1px solid #F5F5F5;
    box-shadow: inset 0 0 25px #E8E8E8, 0 1px 0 #C3C3C3, 0 2px 0 #C9C9C9, 0 2px 3px #333;
    text-shadow: 0px 1px 0px #F5F5F5;
  }

  span.love {
    display: block;
    position: absolute;
    bottom:10px;
    width: 100%;
    text-align: center;
  }
  span.love a {
    text-decoration: none;
    color:#D12026;
  }
  .twitter-follow-button {
    vertical-align: text-bottom;
  }
  .twitter-share-button {
    vertical-align: text-bottom;
  }
<div class="display">
            <div class="wrap">
                <p>Your random value is:</p>
                <div id="h2">Null</div>
                
                <input  class="text-display" type="button" onclick="generateRandomName()" height="50px" width="50px" value="click to input data">
               <!-- <input type="button" onclick="display()" value="display random"> -->
                <br>
                <input id="input1" value="Enter number of Groups">
                <input id="input2" value="Enter number of elements per Group">
                <input type="button" onclick="groupNames()">
            </div>
            
        </div>

Answer №1

One way to improve your code is by utilizing the arr.push() method when adding elements to an array within a for loop. Make sure to declare newArr as an empty array before using it.

Upon reviewing your groups function, it seems like there might be a misunderstanding in your approach. It appears that you are randomly selecting a name from the list and then repeatedly assigning that same name to the new array for each item in the original list.

A helpful technique could be to create pseudo-code outlining the desired steps before translating them into Javascript. This method can assist in identifying any inconsistencies or issues more easily compared to analyzing complex code directly.

I hope these suggestions prove beneficial. Feel free to reach out if you require further clarification or assistance!

Answer №2

Unclear about the purpose of your function groups. It seems to take all the data in arr and place it in newarr with a random sequence. You might want to consider using the .push() method to create a new array instead. This should help streamline your code.

Example:

var newarr = ["David", "Mic"];
newarr.push("Adeline");

Outcome: Your newarr will now contain all 3 names.

Answer №3

Here is my take on your query. I hope this provides some clarity.

    <script>
    var arr = new Array();   
    function yeah()
    {
    arr = prompt("Enter your names").split(",")
    console.log(arr);
    //var random = arr[Math.floor(Math.random() * arr.length)];
    var allStudents ="";

    for(var i=0; i<arr.length; i++) {
        allStudents += arr[i] + "<br/>\n";
    }

     document.getElementById("h2").innerHTML = allStudents;
    }


    function groups()
    {  
        var arr = prompt("Enter your names").split(",");

        var groups = document.getElementById("groups").value;
        var perGrp = document.getElementById("per_grp").value;

        var innerText = "<h4>All</h4> ";
        for(var i=0; i<arr.length; i++) {
            innerText += arr[i] + ",";
        }
        innerText += "<br/>\n";            


        arr = shuffleArray(arr);

        var finalGroups = new Array();

        for(var i=0; i<groups; i++) {
            // assign shuffled elements
            var grpArr = "";
            for(j=0; j<perGrp; j++) {
                grpArr += arr[0] + ",";
                arr.shift(); // removes first element from array    
            }

            grpArr = grpArr.substring(0,grpArr.length - 1);
            finalGroups[i] = grpArr;
        }




        innerText += "<h4>Groups</h4><br/>\n";
        innerText += "<table width='100%' border='1'><tr>\n";           
        for(var i=0; i<groups; i++) {
            // print groups
            var j=i+1;
            var grpArr = finalGroups[i].split(",");
            innerText += "<td>Group " +j+"<br>";
            for(var k=0; k < grpArr.length; k++){
              innerText += grpArr[k] + "<br>";
            }

            innerText += "</td>\n";
        }
        innerText += "</tr></table>\n";

        document.getElementById("FinalGroups").innerHTML = innerText;


   } 

   /**
    * Randomize array element order in-place.
    * Using Durstenfeld shuffle algorithm.
    */
   function shuffleArray(array) {
       for (var i = array.length - 1; i > 0; i--) {
           var j = Math.floor(Math.random() * (i + 1));
           var temp = array[i];
           array[i] = array[j];
           array[j] = temp;
       }
       return array;
   }


</script>
    <style>
    /* Reset */
      * {
            margin: 0;
            padding: 0;
      }

      html,body {
        height:100%;
        margin:0;
        font-family: 'Montserrat', 'sans-serif';
        color:#424242;
        overflow: hidden;
      }
      .display {
        text-align: center;
        display: table;
        height:100%;
        margin:0 auto;
      }
      .wrap {
        display: table-cell;
        vertical-align: middle;
      }
      p {
        font-size: 30px; /* For lamers who don't support viewport sizing */
        font-size:10vmin;
        text-align: center;
        margin: 0;
      }
    #h2 {
        float: center;
        font-size: 10vmin;

        background-size: contain;

    }
      input.text-display {
        display: inline-block;
        color: #5E5E5E;
        font: bold 20px arial;
        text-decoration: none;
        text-align: center;
        margin: 20px auto;
        padding: 15px 20px;
        background: #EFF0F2;
        border-radius: 4px;
        border-top: 1px solid #F5F5F5;
        box-shadow: inset 0 0 25px #E8E8E8, 0 1px 0 #C3C3C3, 0 2px 0 #C9C9C9, 0 2px 3px #333;
        text-shadow: 0px 1px 0px #F5F5F5;
      }

      span.love {
        display: block;
        position: absolute;
        bottom:10px;
        width: 100%;
        text-align: center;
      }
      span.love a {
        text-decoration: none;
        color:#D12026;
      }
      .twitter-follow-button {
        vertical-align: text-bottom;
      }
      .twitter-share-button {
        vertical-align: text-bottom;
      }


    </style>

    <div class="display">
        <div class="wrap">
            <p>Generating Random Groups</p>
            <!--<div id="h2"> </div>

            <input  class="text-display" type="button" onclick="yeah()"  value="click to input data"> -->
           <!-- <input type="button" onclick="display()" value="display random"> -->
            <br>
            <input id="groups" placeholder="Specify number of Groups" >
            <input id="per_grp" placeholder="Specify number of members per Group">
            <br/>
            <input type="button" value="Create Groups" onclick="groups()">
            <div id="FinalGroups"></div>
        </div>



    </div>

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

Combining numerous draggable and droppable functionalities onto a single element

I attempted to include two draggable stop event handlers in a paragraph. However, only the second one seems to fire. How can I ensure that both of them trigger? <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jq ...

Sending a c# array to a c++ function

Currently, I am working with a CLR class library in c++ that looks like this: namespace ANN_Lib { public ref class ANN_FF_BP { private: int neurons; int inputs; int outputs; double **wi; double *wl; ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

How can you utilize a previously opened window from another page in JavaScript?

One of my challenges involves managing windows in a JavaScript environment. When I open a child window using window.open("http://foobar","name"), it reuses the same window when opened with the same name, which is exactly what I want. However, if the origi ...

Utilize the boost library to extract elements from an array within a JSON file

I have a file in JSON format that is structured as follows: { "type": "2D", "data": [ [ "26", "17", "1" ], [ "13", ...

JavaScript does not disappear after employing ajax

My website has two .php pages, each displaying a few info buttons that can be toggled using the following code: $(document).on("click", ".glyphicon-info-sign", function(){ $(".glyphicon-info-sign").not(this).popover("hide"); $(this).popover("toggl ...

What are some strategies for avoiding data loss when rotating the screen on an Android app?

While using my android application, I encountered an issue when rotating the screen. The main functionality of my android application is to display a real-time ECG (electrocardiogram) signal by receiving it through an audio jack and storing it in a buffer ...

Error encountered during installation of Webpack and webpack-dev-server

I'm currently working on setting up Webpack and Babel for utilizing React without Create React App (CRA). While trying to install webpack-dev-server, I encountered some dependency issues. PS C:\Users\Lebedev\Desktop\projects\ ...

Creating a versatile function for rendering content

I am working on a unique calendar feature that involves using checkboxes for filtering purposes. So far, I have managed to get all the filters functioning correctly by triggering my render event in this manner: //Initiate render event when checkbox is cli ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

Monochrome Effect Triggered by Cursor Hover

I'm attempting to use Javascript with HTML5 canvas to convert an image to greyscale, but I seem to be missing something in my code. Can anyone spot the error? I feel like I'm very close! function grayscaleConversion(str) { // Access the Canv ...

Effortless symmetric AES encryption straight from your browser

I have been tasked with developing a basic encryption add-on for a simple knowledge base/article application. The goal is to implement straightforward symmetric encryption without any complex features or a multitude of options. While searching for JavaScr ...

This is my first experience with a Vue/webpack application, and surprisingly, there is no webpack

I am facing an issue with my app not properly loading css files. I suspect it has something to do with the fact that my app is utilizing webpack, but I am unable to locate a webpack.config.js file in the root directory. Instead, I have found webpack.base. ...

Read the characters from the stream

Is there a specific class available for stream reading that allows me to read only a certain number of char from a string or byte from a byte[]? For example, when reading a string: string chunk = streamReader.ReadChars(5); // Read next 5 chars And when ...

Using Angular's ng-repeat prefilter with JavaScript

Is it possible to achieve the functionality of this angular js filter ng-repeat on a tr element using pure javascript? Could it be done in just one custom filter? Please note that showRow is a function that returns a boolean value, and searchString is a s ...

Tips for modifying an object within a nested array in a mongoose schema

I've come across many questions like this one, but no answers yet. Issue Imagine I have the following mongoose schema: const mySchema = new mongoose.Schema({ sanePeoplesField: String, comments: [ normalStuff: {type: Date, default: Date.now} ...

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

Incorporate CSS animations prior to removing an element from an array

Before removing an item from my data table, I want to implement a CSS animation. The deletion is initiated by the @click event. I would like to preview the effect of my animation (class delete_animation) before proceeding with the actual removal. var vm ...

Maximizing conditional evaluation in typescript

I have the following JavaScript code where I am displaying different status based on the response key from an API. Is there a more efficient approach to optimize this code so that I don't have to check each case with IF, especially if the number of st ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...