skip to Main Content

I’m new to programming and I wanted to make a word frequency counter where it finds the most frequent word and has it pop up as an alert. Although I have read some articles I can’t seem to find a proper solution. For example, I want my alert to say the most frequent word in the text area is "Hello" 2. Any help will be appreciated.

enter image description here

function countWords() {
    let input = document.getElementById("input").value;
    var counter;
    for(var i = 0; i < input.length; i++) {
        if(input[i] == input[i+1]){
            counter = counter + 1;
        }
    }
    alert(counter);
}
<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="main.js"></script>
</head>

<body>
    <textarea id="input" rows="30" cols="30"></textarea><br>
    <button type="button" onclick="countWords()">Count Repeated Words</button>
</body>
</html>

2

Answers


  1. Here’s a method to do everything you’re looking for, broken down with comments:

    function countWords() {
    
      // use regex match to extract all words from input into an array
      let input = document.getElementById("input").value
        .toLowerCase()
        .match(/[a-z']+/g);
    
      // loop through input array counting instances of each word
      const count = {};
      input.forEach((word) => {
        if (count[word]) {
          count[word]++;
        } else {
          count[word] = 1;
        }
      });
    
      // convert count to key/value pairs, then sort by value amounts
      const sortedCount = Object.entries(count).sort((a, b) => b[1] - a[1]);
    
      // will alert: hello 2 (because hello appears twice)
      alert(sortedCount[0][0] + ' ' + sortedCount[0][1]);
    }
    <textarea id="input" rows="6">
    Hello, how are you doing today?
    I'm good, hello to you as well!
    </textarea>
    <br />
    <button type="button" onclick="countWords()">Count Repeated Words</button>
    Login or Signup to reply.
  2. Here’s a solution, tried to comment each step:

    function countWords() {
      let input = document.getElementById("input").value;
      let counters = {};
    
      input
        // to lower case
        .toLowerCase()
        // split on space
        .split(' ')
        // remove non word - characters (.! etc)
        .map(x => x.replace(/W/g, ''))
        // count number of occurences of each word
        .forEach(x => counters[x] = (counters[x] || 0) + 1);
    
      // sort counters
      let byOccurence = Object.entries(counters)
        .sort((a, b) => b[1] - a[1]);
    
      alert(
        'The 5 words that occur the most times are:n' 
        + byOccurence.slice(0, 5).map(([word, times]) =>
          `${word} ${times}n`).join('')
      );
    
    }
    
    countWords();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search