Last active
August 29, 2015 14:22
-
-
Save paultannenbaum/f1f43ea322e2a954df7d to your computer and use it in GitHub Desktop.
Question: Tell us the 10 most frequent letters, in order, occurring in the 1000 most common words listed on this page: http://www.giwersworld.org/computers/linux/common-words.phtml. Bonus points if you can do this in vanilla js (no jQuery).
This file contains hidden or 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
| /** Steps **/ | |
| // 1.) First Grab the 1000 words and put into an array: | |
| var wordArray = document.getElementsByTagName('pre')[0].innerHTML.split("\n"); | |
| var characterArray = document.getElementsByTagName('pre')[0].innerHTML.replace(/\n/g,'').split(''); | |
| // 2.) Create an object which stores character by frequency, and create a sorting function | |
| var characterObj = {}; | |
| var populateCharacterObjByFrequency = function(string) { | |
| for (var i=0; i<string.length; i++) { | |
| var character = string.charAt(i); | |
| if (characterObj[character]) { | |
| characterObj[character]++; | |
| } else { | |
| characterObj[character] = 1; | |
| } | |
| } | |
| }; | |
| // 3.) Run the function on each array item | |
| wordArray.forEach(function(item) { | |
| populateCharacterObjByFrequency(item); | |
| }); | |
| // 4.) Turn that object into an array of sub arrays | |
| var characterArr = []; | |
| for (var key in characterObj) { | |
| characterArr.push([key, characterObj[key]]) | |
| } | |
| // 5.) Sort array by value (highest to lowest), and give back the first 10 | |
| characterArr.sort(function(a,b) { a[1] - b[1] }).reverse.slice(0, 10); | |
| /** Final Code **/ | |
| var wordArray = document.getElementsByTagName('pre')[0].innerHTML.split("\n"); | |
| var characterObj = {}; | |
| var characterArr = []; | |
| var populateCharacterObjByFrequency = function(string) { | |
| for (var i=0; i<string.length; i++) { | |
| var character = string.charAt(i); | |
| if (characterObj[character]) { | |
| characterObj[character]++; | |
| } else { | |
| characterObj[character] = 1; | |
| } | |
| } | |
| }; | |
| wordArray.forEach(function(item) { | |
| populateCharacterObjByFrequency(item); | |
| }); | |
| for (var key in characterObj) { | |
| characterArr.push([key, characterObj[key]]) | |
| }; | |
| characterArr.sort(function(a,b) { b[1] - a[1] }).slice(0, 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment