Going through some problems in Code Wars and Hackerrank, I have been faced with a few instances where I need to know the number of times something appears. Initially, I would set up an empty Array, iterate through the Array in question, and check for duplicate characters only to push them into my empty Array. At the end of the attempt, things would end up looking very messy.
After some research, I found that there is a frequency hash that exists thanks to some StackOverflow reading. What is done, is that an empty hash(object) is created and you are checking the hash for a key-value pair. If that does not exist, you are setting a key in the hash with a value of 1, otherwise, if it does exist, you are incrementing that value by 1. Let us walk through this below:
We will set up a string with a value of “big black cat”, this will be the string passed through. What we will then do is set up a function that can be called anything but will take in a parameter, and that argument will be a string. This string will be “split()” to be an Array. The entire code is below with explanations on what is happening per line, along with what it will return.
With this simple function, we can find out how many times a character occurs within an array when looping through this. There may be simpler ways to do this, but this is the easiest way I have found.. so far. When we return count, this will bring back an object that lets us know there are 2 b’s, a’s, c’s, and even 2 spaces in the string “big black cat”; and 1 occurrence of every other letter, as seen below:
I hope this helps anybody reading this solve a few problems as it has helped me. One thing that I got stuck on was the ternary logging. Since the key-value pair does not exist, the false condition needs to be setting the value to 1, then increment if true. Good luck to all of you problem solvers!