Explore the input from multiple users to uncover the word that appears most frequently among them

Hey there (brand new to JavaScript), I am working on a simple program that requires input from multiple users through prompt pop-ups.

For example:

<script type="text/javascript>
    var userInput = prompt("Enter your input:");
</script>

It's pretty basic code, right? I'm still getting the hang of it!

My current challenge is to create a script that can analyze user inputs and display the most commonly occurring word. Is there a way to write a program that can achieve this and then use document.write to output the result?

If anyone has any tips or suggestions, please feel free to share. I appreciate any help as I am struggling with this concept at the moment.

Answer №1

If we were to use only pure Javascript, imagine a scenario where you ask the user for input on a webpage three times. Each response is then stored in an array.

var prompts = [];
(function(){
    for (var i=0; i<3; i++) {
        prompts.push(prompt("What is your favorite color?"))
    }
    //...
}());

Next, we would need a function to go through each response and identify the words that are repeated.

function collateWords () {
    var sWords = prompts.join(" ")
        .toLowerCase().trim().replace(/[,;.]/g,'')
        .split(/[\s\/]+/g).sort();
    var iWordsCount = sWords.length;

    var counts = {};
    for (var i=0; i<iWordsCount; i++) {
        var sWord = sWords[i];
        counts[sWord] = counts[sWord] || 0;
        counts[sWord]++;
    }

    var arr = [];
    for (sWord in counts) {
        arr.push({
            text: sWord,
            frequency: counts[sWord]
        });
    }

    return arr.sort(function(a,b){
        return (a.frequency > b.frequency) ?
            -1 : ((a.frequency < b.frequency) ? 1 : 0);
    });
};

Execute the new function and display the results on the page.

//...
var collected = collateWords();
var iWordsCount = collected.length;
for (var i=0; i<iWordsCount; i++) {
    var word = collected[i];
    document.write(word.frequency + ", " + word.text);
}
//...

For a complete example, visit http://jsfiddle.net/jdgiotta/n26j5xf0/

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

What is the process for including a file in a request?

I've been encountering an issue while trying to upload a CSV file and send a request to an API. Despite attempting to do so via XHR, Unirest, and Axios, none of these methods seem to be working properly. Could there be something amiss with the impleme ...

Implementing a validator based on the operator selection in react-querybuilder

Is it possible to add validators to fields that are only active when using the like operator? For example, if the like or unlike operators are used in the phoneNumber field without the % sign, it should be invalid. If the = operator is used, the % sign sho ...

Verifying API access with custom settings using the got module

I'm having some trouble with a basic API call that requires authentication using the got library. I tried using the options parameter to pass my username and password, but I keep getting an HTTPerror. Could someone please review my usage of the optio ...

Attempting to iterate over an array and utilize a foreach loop to return several sets of data

In my original code, getProductInfo took two parameters (res, sku). However, I now want to pass a set object containing SKU numbers and for each SKU, send the data using res.send. const activeProductBank = new Set([6401728, 6430161, 6359222, 6368084]); g ...

Is it possible to dynamically adjust the Semantic UI Progress bar according to the data stored in mongoDB?

I am facing an issue with displaying the progress of a job on the UI in real-time. Every 5 seconds, I retrieve the job progress and store it in mongoDB. I tried using Semantic UI progress bar in my meteor project, but the progress is not incrementing as ex ...

Using jQuery to select a nested element in HTML

After choosing $("a.tp[programm='" + programm + "']"); I am looking to target the nested element span.thump and update its text content. How can I achieve this? <h4><a programm="74" class="tp" href="#"><img src="/images/tuo.png ...

How does AJAX relate to XML technology?

Well, let's clear up this misconception about XML and AJAX. The term "Asynchronous JavaScript And XML" may seem misleading because you can actually use an XMLHttpRequest object to fetch not just XML, but also plain text, JSON, scripts, and more. So w ...

Creating unique border-radius for each point in a Highcharts column chart with React

Let's flip the script and start at the finish line. My goal is to customize my column chart to resemble this design: https://i.stack.imgur.com/FckJB.png Creating this style is a breeze with chart.js Credit: I've already delved into this inquiry ...

Grails 3.1.9 does not support displaying JavaScript

Having trouble getting the datepicker to display using JavaScript <script> $( "#invoiceDate" ).datepicker({ inline: true, dateFormat: "yy-mm-dd", onSelect: function(datetext){ datetext = datetext+" 00:00:00.0" ...

Issue with displaying ChartJS on Django HTML page

I am attempting to create a horizontal bar chart in HTML, but unfortunately, it is not displaying correctly. I have sent 2 variables from views.py, which are {{top5StockCode}} and {{top5TotalSales}}. The values of {{top5StockCode}} that were sent from vi ...

Angular: sending the user input to the component

I'm trying to link the value of an HTML input field to a variable 'numToAdd' in my component, and then increment the 'numToAdd' variable by 1. However, I'm facing difficulties passing the input value to the component variable. ...

Tips on making a fresh form appear during the registration process

After clicking on a submit button labeled as "continue" within a form, a new form will appear for you to complete in order to continue the registration process. ...

Is it possible to call componentDidMount() multiple times in React?

I am in the process of converting an HTML API to ReactJS. The original HTML API is as follows: <script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608"></script> <script> var mapContainer = document.getE ...

Access the file and execute JavaScript code concurrently

Can I simultaneously link to a file as noticias.php and call a JavaScript function? <a href="javascript:toggleDiv('novidades');" class="linktriangulo"></a> The toggleDiv function in my noticias.php file: function toggleDiv(divId) { ...

Automating the linking of tsd definitions with bower and npm: A step-by-step guide

Currently, I am in the process of transitioning an existing project to TypeScript which includes numerous bower and npm dependencies (bower.json and package.json). As mentioned on the tsd github page, TSD facilitates the discovery and linking of defini ...

Tips for integrating and showcasing API data in your React JS application by utilizing React Table and Axios

I am just starting out with React and I am faced with the task of fetching data from an API and displaying it in a table. I have decided to use React Table for this purpose. However, I am encountering some issues with getting the data from the API to sh ...

Handling error reporting using JSON in jQuery AJAX post success

UPDATE: I have resolved the PHP errors mentioned in previous Answers, however, the issue still persists. I am attempting to implement an error message display in case of a failed POST request and a success message for successfully completed requests. Curr ...

Information regarding gender vanishes upon refreshing the page

When the page is refreshed, the variable called jso disappears. Is there an alternative method for storing information that does not involve using a button? The goal is to have it work seamlessly when the page is reloaded without requiring any user action. ...

How to pass command line arguments into Chrome using WebDriverIO Selenium from the config.js file

Is there a way to add the disable-web-security flag for Chrome in order to conduct UI tests? How can I incorporate commands into the wdio.config file () to achieve this? capabilities: [{ browserName: 'chrome' }] ...

What is the best practice for adding one string to the end of another?

So, is this the best way to concatenate strings in JavaScript? var str = 'Hello'; str += ' World'; While most languages allow for this method of string concatenation, some consider it less efficient. Many programming languages offer a ...