JSFiddle - React, Tailwind, and code Playground
by Liam Talbot
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<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]);
}
}
}
}
}
});
var sortedWords = _.sortBy(words, [function(o) { return o[1] * -1; }]);
var result = '';
_.forEach(sortedWords, function (word) { result += '<br />' + word[0] + ' - ' + word[1]; });
document.getElementById('result').innerHTML = result;
const mostOccurring = sortedWords[0][0];
document.getElementById('result').innerHTML = document.getElementById('result').innerHTML + '<br /><br />var mostOccurring is: ' + mostOccurring;