1

i created a simple hashtags tool with js in local.

Extract from text, count and order hashtags by count DESC in js local.

Problem: The ordering is based on alphabetic occurence and i want to sort by count DESC (like sql query) see the result on demo link

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;
}

All the code below come from different stackoverflow answers.

Here is a working demo on codepen

Before asking here, i tried this answer but the result is wrong when numbers over 10 are ordered with the rest (exemple : 1 < 12 < 2 < 28 < 30

4
  • 1
    This should help: How to sort an array of integers correctly. Commented Mar 9, 2018 at 13:25
  • @FelixKling thanks but it does not help me. Solutions are only for sorting integers, and i want to sort a pair "key:value(int)" so it's a bit more complicated... Commented Mar 9, 2018 at 13:37
  • 1
    In your question you are saying that you want to order the values by "count", not by key. Does this not do what you want? Object.keys(freq).sort((x, y) => freq[y] - freq[x]).forEach(...). Commented Mar 9, 2018 at 13:43
  • @FelixKling YES it do what i want! Thanks for your help and sorry for my bad english.. Commented Mar 9, 2018 at 13:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.