I have been attempting to eliminate duplicates from my array and determine the frequency of each word appearing in the array. While I have come across methods to address this issue, none of them seem to be working. For instance, when I input the text "this this is a test test," the final sorted list is:
1 - is
1 - a
2 - this
2 - test
Although I intend to eventually reverse the array so that the highest numbers appear first, this result is exactly what I am looking for! However, changing the text slightly to something like "this is a test test this" completely disrupts the order:
1 - this
1 - is
1 - a
1 - this
2 - test
Here, 'test' appears twice as expected, but 'this' shows up twice in the list with a count of '1' each time. This only occurs for consecutive duplicates. How can this be prevented?
Below is the code snippet I am currently using:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after splitting.</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 number 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>