JSFiddle - React, Tailwind, and code Playground
by Liam Talbot
HTML
<div id="test">
If the below code goes through my webpage text and counts all instances of words and outputs in the dev console. How could I add a sort function that sorts this to display words with highest number of instances or integer counted, and then stores said highest counted word in a variable that I could use later?
</div>
<div id="result">
</div>
JavaScript
var words = [];
var walkDOM = function (node, func) {
func(node);
node = node.firstChild;
while(node) {
walkDOM(node, func);
node = node.nextSibling;
}
};
walkDOM(document.getElementById('test'), function (node) {
if (node.nodeName === '#text') {
var text = node.textContent;
text = text.replace(/[^A-Za-z]/g, ' ');
text = text.split(' ');
if (text.length) {
for (var i = 0, length = text.length; i < length; i += 1) {
var matched = false,
word = text[i];
if (word) {
for (var j = 0, numberOfWords = words.length; j < numberOfWords; j += 1) {
if (words[j][0] === word) {
matched = true;
words[j][1] += 1;
}
}
if (!matched) {
words.push([word, 1]);
}
}
}
}
}
});
words.sort(function(a, b) { return b[1] - a[1]; });
var result = '';
words.forEach(function (word) { result += '<br />' + word[0] + ' - ' + word[1]; });
document.getElementById('result').innerHTML = result;
const mostOccurring = words[0][0];
document.getElementById('result').innerHTML = document.getElementById('result').innerHTML + '<br /><br />var mostOccurring is: ' + mostOccurring;