2021年2月2日星期二

Object property descending order in Javascript

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:

Example

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>
https://stackoverflow.com/questions/66020883/object-property-descending-order-in-javascript February 03, 2021 at 11:34AM

没有评论:

发表评论