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