How can I determine the most frequently used word?

81 views Asked by At

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>

1

There are 1 answers

3
Thomas Frank On BEST ANSWER

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();