Skip to content

Instantly share code, notes, and snippets.

@troyleach
Created March 28, 2015 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save troyleach/e96ffebcc9498e71ea5d to your computer and use it in GitHub Desktop.
Save troyleach/e96ffebcc9498e71ea5d to your computer and use it in GitHub Desktop.
count the frequency of given letters
// Write a function charFreq() that takes a string and builds a frequency listing of the characters contained in it.
// Represent the frequency listing as a Javascript object.
// Try it with something like charFreq("abbabcbdbabdbdbabababcbcbab").
// I got a lot help from stack on this one. I had no idea how to make a object from a string.
// and in doing research for that I found a solution to something similar to this. But I do understand
// how every line of code works and why!
function charFreq(source) {
var frequency = {};
for (var i = 0; i < source.length; i++) {
var character = source.charAt(i);
if (frequency[character]) {
frequency[character]++;
} else {
frequency[character] = 1;
}
}
return frequency;
};
console.log(charFreq("aabbabcbdbabdbdbabababcbcbab"));
@Nyaaimee
Copy link

Nyaaimee commented Dec 5, 2022

pls can you explain each line of code for better understanding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment