Skip to content

Instantly share code, notes, and snippets.

@albertstartup
Created August 1, 2015 02:22
Show Gist options
  • Save albertstartup/b4298c6e33b3366bb856 to your computer and use it in GitHub Desktop.
Save albertstartup/b4298c6e33b3366bb856 to your computer and use it in GitHub Desktop.
get an array of arrays which hold a string and number of occurences
function getWordOccurences() {
var textNodes;
function getTextNodes() {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
var node;
var textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node.nodeValue);
}
return textNodes;
}
var sortByOccurence = function(arr){
var occurenceMap = {};
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
if (occurenceMap[el] == null) {
occurenceMap[el] = 1;
} else {
occurenceMap[el]++;
}
}
return sortByValue(occurenceMap);
};
function sortByValue(obj) {
var sortable = [];
for (var word in obj) {
sortable.push([word, obj[word]]);
}
sortable.sort(function(a, b) {
return b[1] - a[1];
});
return sortable;
}
textNodes = getTextNodes();
return sortByOccurence(textNodes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment