Last active
April 29, 2016 20:31
-
-
Save itsanna/792034327d86ff2109c80672a4c46c93 to your computer and use it in GitHub Desktop.
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
/* | |
Given a page of text, output the characters ordered from highest to lowest occurrence. | |
for example, the output for 'banana!' is | |
a: 3 | |
n: 2 | |
b: 1 | |
!: 1 | |
*/ | |
var pageoftext = 'banana!' | |
function findFrequency (text) { | |
var letters = {} // { a: 2, b: 10 } | |
// iterate through each letter | |
for (var i = 0; i < text.length; i++) { | |
var character = text.charAt(i) | |
if (character !== ' ') { | |
// make sure it is not a space | |
if (letters[character]) { | |
letters[character] += 1 | |
// add letter to object if it doesn't already exist | |
// if letter exists, add to the count | |
} else { | |
letters[character] = 1 | |
} | |
} | |
} | |
var arr = [] | |
for (var key in letters) { | |
arr.push([key, letters[key]]) | |
} | |
// [ ['b', 1], ['a', 2], ['!', 1] ] | |
// sort the properties of object according to values | |
arr.sort(function(a, b) { | |
return b[1] - a[1] // reverse order, highest to lowest | |
// if < 0, sort a to a lower index than b | |
// if > 0, sort b to a lower index than a | |
// if 0 leave it | |
}) | |
return arr | |
} | |
console.log(findFrequency(pageoftext)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment