Created
August 1, 2015 02:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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