I'm trying to remove duplicates from my array and display the number of times that a particular word shows up in the array. I've seen ways to handle this, but I tried the ones I've found, and they're not working. When I enter text such as "this this is a test test," it will return a final sorted list of:
1 - is
1 - a
2 - this
2 - test
Though I will eventually be reversing the order of the array, so that the highest numbers are first in the list, this result is perfect! But, if I change the text up a bit, to something like "this is a test test this," the order goes completely out of whack, as shown here:
1 - this
1 - is
1 - a
1 - this
2 - test
As you can see, 'test' shows 2x, which is great, but 'this' shows up twice in the list with only a number '1'. It only compiles duplicates that are in succession. How do I prevent this?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="analyze()">Analyze</button>
<p id="displayText"></p>
<script>
function compareWordCount(a,b) {
  if (parseInt(a) < parseInt(b))
    return -1;
  return 1;
}
function analyze() {
    var str = "this is a test test this";
    var res = str.split(" ");
    document.getElementById("displayText").innerHTML = res;
    document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";
    document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";
    var words = [];
    var wordsWithCount = [];
    for (i = 0; i < res.length; i++) {
        words.push(res[i]);
        document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
    }
    var current = null;
    var cnt = 0;
    for (var i = 0; i < words.length; i++) {
        if (words[i] != current) {
            if (cnt > 0) {
                document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
                wordsWithCount.push(cnt + " - " + current);
            }
            current = words[i];
            cnt = 1;
        } else {
            cnt++;
        }
    }
    if (cnt > 0) {
        document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
        wordsWithCount.push(cnt + " - " + current);
    }
    wordsWithCount.sort(compareWordCount);
    document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";
    for (i = 0; i < wordsWithCount.length; i++) {
        document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
    }
}
</script>
</body>
</html>
 
     
     
     
    