I'm building a program in Javascript that takes a String as an input (inputTextLower
), counts how many times each word was used (similar function to: http://www.writewords.org.uk/word_count.asp), and then displays the frequency of each word in an HTML table. The word frequency counter works fine, but the results are not displaying in order of descending frequency, they're displaying in order of the words in inputTextLower
. How can I order the results by frequency? Here's an image to clarify:
And here's my text frequency function and how I'm entering the results into the table:
let tableText = document.querySelector('table'); let inputTextLower = "This is a test test test sentence sentence".toLowerCase(); var pattern = /\w+/g, string = inputTextLower; matchedWords = string.match(pattern); var counts = matchedWords.reduce(function(stats, word) { if (stats.hasOwnProperty(word)) { stats[word] = stats[word] + 1; } else { stats[word] = 1; } return stats; }, {}); for (const word in counts) { if (counts[word] == 1) { tableText.innerHTML += `<tr><td>${word}</td><td>${counts[word]} time</td></tr>`; } else { tableText.innerHTML += `<tr><td>${word}</td><td>${counts[word]} times</td></tr>`; } }
<table></table>
没有评论:
发表评论