按计数DESC javascript

时间:2018-03-09 13:18:04

标签: javascript hashtag

我用本地的js创建了一个简单的主题标签工具

从js local中的count DESC中提取文本,计数和排序主题标记。

问题:排序基于字母出现,我想按计数排序DESC(如sql查询)在演示链接上查看结果

HTML

<h2>#Hashtag Cloud</h2> 
<button onclick="extractHashtags()">Extract #hashtags</button>
<button onclick="countHashtags()">Count #hashtags</button>
<textarea id="inputTextToSave" cols="100" rows="5">#Hello this #is 
a text with #lot of #hashtags #hello #hello #The #quick #brown #fox 
#jumps #over #the #lazy #dog #The quick brown fox jumps over #the 
#lazy dog</textarea>

JS

function extractHashtags(){
  var textToSave = document.getElementById("inputTextToSave").value;
  textToSave = textToSave.toLowerCase()
  var number_regex = /((?:|^\s)(?:#)([a-zA-Zà-úÀ-Ú\d]+))/g;
  var matches = [];
  textToSave.replace(number_regex, function(match)
    {
    matches.push(match);
    });
  //alert(matches);
  document.getElementById("inputTextToSave").value = matches;  
}

function wordFreq(string) {
    var words = string.replace(/[.]/g, '').split(/\s/);
    var freqMap = {};
    words.forEach(function(w) {
        if (!freqMap[w]) {
            freqMap[w] = 0;
        }
        freqMap[w] += 1;
    });

    return freqMap;
}

function countHashtags(){
  var $inputTemp = document.getElementById("inputTextToSave").value; 
  $inputTemp = $inputTemp.replace(/,/gi, ' ');

  var freq = wordFreq($inputTemp);
  var $test ='';
  Object.keys(freq).sort().forEach(function(word)
    {
    // $test += word + "(" + freq[word] + "), ";
    // occurence: 'count',
    $test += word + ":" + freq[word] + ", ";
    });

  document.getElementById("inputTextToSave").value = $test;
}

以下所有代码都来自不同的stackoverflow答案。

在codepen上

Here is a working demo

在问这里之前,我尝试了this answer但是当其余数字超过10时,结果是错误的(例如:1&lt; 12&lt; 2&lt; 2&lt; 28&lt; 30&lt; 30

0 个答案:

没有答案