creating arrays of random names for groups in javascript

I'm a beginner at coding in JavaScript and I'm attempting to shuffle a list of names that are inputted in a textarea. The user selects the desired number of groups, clicks shuffle, and the divided groups are displayed as the output result. Below is the code I have so far, but it's not functioning correctly. Can someone please help?

<script>

    function ArrayToGroups(source, groups){
        var groupList = [];

        groupSize = Math.ceil(source.length/groups);

        var queue = source;

        for(var r = 0; r < groups; r++){
            groupList.push(queue.splice(0,groupSize));
        }
        return groupList;
    }

    function textSpliter(splitText){

        var textInput = document.getElementById("inputText").value;
        var splitText = textInput.split(',');

        var newList = []; 

        for(x = 0; x <= splitText.length; x++) {
            var random = Math.floor(Math.random() * splitText.length);

            var p = splitText[random];
            newList.push(p);

            splitText.splice(p,groupList);
        }

        for(var i = 0; i < newList.length; i++){

            var s = newList[i];
            document.getElementById('resInput').value += s + "\n" ;
        }

        return splitText;
    }



</script>

Below are my input and output textareas

</head>
<body>
<form>
    <textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
    <input type="number" name="number" max="6" value="1" id="groupNumber">
    <textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
    <input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>

Answer №1

function mixUpList() {

    // Get user input list
    // Example: item1, item2, it em 3, ...
    var userList = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");

    // Get number of groups desired
    var groupCount = parseInt(document.getElementById("groupNumber").value);

    // Calculate number of items per group
    var itemsPerGroup = Math.floor(userList.length / groupCount);

    // Check if there are enough elements to form equal groups
    if (groupCount * itemsPerGroup == userList.length) {

        // Initialize an array to store the groups
        var allGroups = new Array();

        for (i = 0; i < groupCount; i++) {

            allGroups[i] = new Array();

            for (j = 0; j < itemsPerGroup; j++) {

                // Select a random index from the list
                randomNumber = Math.floor(Math.random() * userList.length);

                // Add the selected element to the group
                allGroups[i][j] = userList[randomNumber];

                // Remove the selected element from the main list
                userList.splice(randomNumber, 1);
            }

        }

        // Prepare the output text
        var resultText = "";

        for (i = 0; i < groupCount; i++) {

            resultText += "Group " + (i + 1) + ": ";

            for (j = 0; j < itemsPerGroup; j++) {

                if (j != 0) { 
                    resultText += ", "; 
                }
                resultText += allGroups[i][j];

            }

            resultText += "\n";

        }

        // Display the result in the designated area
        document.getElementById("resultArea").value = resultText;

    } else {

        alert("Please add more elements to evenly distribute into groups");

    }

}

Answer №2

I have rewritten your code for better clarity.

FIDDLE

function textSpliter() {
    var inputText = document.getElementById("inputText").value;
    var namesArray = inputText.split(",");

    var groupNumber = document.getElementById("groupNumber").value;
    var totalGroups = Math.ceil(namesArray.length / groupNumber);
    var groupsArr = [];

    for (var i = 0; i < totalGroups; i++) {
        var group = [];
        for (var j = 0; j < groupNumber; j++) {
            var randomIndex = Math.floor(Math.random() * namesArray.length);
            var namePicked = namesArray[randomIndex];
            if (namePicked != undefined) {
                group.push(namePicked);
                namesArray.splice(namesArray.indexOf(namePicked), 1);
            }
        }
        group.sort();
        groupsArr.push(group);
    }
    printResult(groupsArr);
}

function printResult(groupContent) {
    var resultOutput = document.getElementById("resInput");
    resultOutput.value = "";
    for (var i = 0; i < groupContent.length; i++) {
        var currentGrpContent = "";
        for (var j = 0; j < groupContent[i].length; j++) {
            currentGrpContent = groupContent[i].join(",");
        }
        resultOutput.value += currentGrpContent + "\r";
    }
}

Answer №3

Here's the ES6 version of the text splitting function ;-)

Click here for the code snippet

const textSpliter = () => {
  const input = document.getElementById("inputText").value;
  let names = input.replace(/\s*,\s*|\n/g, ",").split(",");

  const groupSize = document.getElementById("groupNumber").value;
  const groupCount = Math.ceil(names.length / groupSize);
  const groups = Array.from({ length: groupCount }, () => []);

  let i = 0
  while (names.length > 0) {
    const m = Math.floor(Math.random() * names.length);
    groups[i].push(names[m]);
    names.splice(m, 1);
    i = (i >= groupCount - 1) ? 0 : i + 1
  }
  printGroups(groups);
}

const printGroups = (groups) => {
  const output = document.getElementById("resInput");
  output.value = groups.map(group => group.join(',')).join('\r');
}

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

Refresh a DIV using two SQL queries in forms

I am encountering an issue with updating a single div element using the results from two different forms on an HTML page. I want either form1 or form2 to display results in the same div element, and it should be updated with one line of content fetched fro ...

Switch out a section of a hyperlink with jQuery

I am currently working with an 'iframe' that loads up a page containing multiple external links. My goal is to modify these links so that they redirect to 'Youtube' instead. For instance, one of the links on the page appears as follows: ...

Error in test runner: Cannot convert type 'Cucumber' to type '? extends Runner' in Java cucumber

I'm currently working on setting up the Cucumber framework using Java for running my tests, but encountering a type mismatch error in the Test Runner. package cucumbertest; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import ...

Using ASP.NET MVC to transmit JSON information to a Controller method

Even after multiple attempts, I am unable to send JSON data to my ASP.NET MVC3 controller action method successfully. Below is the ajax call I am using (it utilizes the JSON.stringify method from json2.js): $.ajax({ url: '/Home/GetData', ...

Utilize the Nextel API to send SMS messages with the sender's number clearly displayed in

Hello, I am currently utilizing the Vonage API to send SMS messages through my Node JS application. Although the receiver does successfully receive the message, it appears as though it is coming from an anonymous number. Is there a way to modify the "Fro ...

The module specifier "logrocket" could not be resolved, make sure to use either npm or

I'm currently having an issue with initializing LogRocket. I followed the steps from the official documentation: I successfully installed it using node: npm i --save logrocket However, when trying to initialize it on my page earlier with: < ...

When the mouse hovers over a specific area, a sIFR element

Here is the html code that I am working with: <li><a href="#"><span class="font Berthold-light">1</span>Consectetur adipiscing elit risus.</a></li> I have successfully replaced the number within the span using sIFR. Ho ...

What is the most efficient way to group object values with the same property value into the same subarray using Javascript?

I need help with organizing data in an array. I have an array with 190 objects, each containing six keys and values, shown here: https://i.sstatic.net/a1gmh.png My objective is to create a new array that groups the values by year, like this: [ [2000 ...

Using JavaScript includes to verify the presence of various values

let colorSet = ["black", "red", "pink", ]; This is the colorSet array. I can easily check if a specific value is present in the colorSet array. For example, to check if "red" is present in the array, I can use the following code: let isRedPresent = color ...

What is the best way to pass the second variable to the Vue Laravel component and have it automatically set to the input variable by default?

I'm new to learning Vue and I'm wondering how to pass 2 values to my component. Can you help me with my code? <div id="js-autocomplete-region"> <autocomplete-region-component :query-prop="{{ json_encode(old('regionName', $ ...

Tips for embedding React components, kept in an array, within the render function of a separate component

I have a component called Screen that imports another component to display search results. Within the Screen component, there is a method that loops through an array of objects and creates new instances of the search result component for each object. As I ...

a guide on monitoring the status of a stripe transaction through a straightforward form and javascript

Currently, I am in the process of setting up Stripe checkout for my website. I have successfully implemented the payment form, but now I need to figure out how to redirect the user to another page after a successful payment. Below is the JavaScript code th ...

Combining jQuery Functions

I am looking for a way to streamline the code for my buttons and div elements. I have 30 buttons labeled from #p3-btn to #p30-btn, each corresponding to a different effect on the div elements with classes .p3 to .p30. Is there a more efficient way to achie ...

Is there a way to animate a progress bar using jQuery and the percentage unit in a single instance?

Is there a way to smoothly animate my progress bar when I hover over the parent div? I have tried setting the width to "90%", but it animates multiple times if I hover over the parent div more than once. Using pixel units fixes this issue, but it is not re ...

Create a string according to the size of the given list

If I have an array that contains the following elements: arr = [1,2,3,4] I wish to create a string similar to this format using the array. '{(%s),(%s),(%s),(%s)}' % (arr[0], arr[1], arr[2], arr[3]) However, I would like the length of the stri ...

Issue in Jasmine test: 'Spy should have been invoked'

I've encountered an issue while writing a Jasmine test case for the following Angular function. The test case failed with the message "Expected spy [object Object] to have been called". $scope.displayTagModelPopup = function() { var dial ...

React is displaying [object object] instead of the intended JSX in the user interface

My React code is displaying [object object] instead of the JSX in the UI. Here is my code: const renderIntended = (column, data, type, row) => { let value = data; const treeHtml = `<div class="tree-link" style=&apos ...

Stacking divs by rotating them on top of each other

It seems like I'm facing a quick fix issue that's really messing with my mind. Here's the situation: I have a custom dashboard with multiple divs containing rotating data. However, when the page refreshes for the first time, all the data loa ...

I'm receiving an npm error that says "Module '/home/directory' not found in '/home/directory'. Can anyone help me troubleshoot this issue?

I've configured the following script in my package.json file "scripts": { "start": "watchify -o js/bundle.js -v -d ." } Whenever I try to run npm start from within the /home/directory, I encounter the following error: Error: Cannot find modul ...

Re-apply modified AngularJS code in the console using Chrome Dev Tools after making changes or fixing errors

I have encountered a peculiar situation that I have successfully dealt with before, but the correct syntax escapes my memory at the moment. Let's say I have an angularJS application named myAngularApp in the code. In the app.js file, it looks somethin ...