Coding/Blog challenge 12

Coding/Blog challenge 12

Today's challenge was a codewars challenge, but I've seen the similar problems on other sites. This is a good one, though, so enjoy!

The Challenger

challenge12.png

I remember when first learning objects & key/value pairs, it was a bit confusing. So, the first time I encountered a similar problem, I struggled for a long time finding a solution. This time, I am happy to report that it was much easier.

First, I want to create the function and define a container object to hold my key/value pairs.

function count(string) {
    //our container object to be output
    let output = {};

    return output;
}

I then want to loop over the argument string. We also know that we need to have each letter that appears in the string to be our object's keys. So, we can assign a variable to be the current index of the argument string.

function count(string) {
    let output = {};

    for (let i = 0; i < string.length; i++) {
        //every iteration this variable will be assigned to the current letter of string
        let key = string[i];

        }
    }
    return output;
}

At this point, we really need to break down what we need to do to solve this. For each iteration of the loop, If the key exists, we want to accumulate the value by 1. If this letter doesn't exist as a key in our object, we want to assign that key to be our current letter & assign the value to be 1. After we've iterated over the whole argument, our output obj should be returned.

function count(string) {
    let output = {};

    for (let i = 0; i < string.length; i++) {
        let key = string[i];

        //if letter already exists in obj, accumulate
        if (output[key]) {
            output[key]++;

        } else {
            //if not then the value will be one
            output[key] = 1;
        }
    }
    return output;
}

Other solution

Some other people's solutions were really cool to see and breakdown. I honestly think reading and breaking down other people's code is a great way to level up your learning. This is a great way to start doing so.

Here's another solution I found interesting. They start by splitting the argument's string into an array. Then it utilizes the higher order function forEach. After this, the ternary operator is used to check if the current letter that's being looped over exists as a key already. If it does, the value accumulates by 1 if not the current letter is set as a key with a value of one.

function count (string) {  
  var count = {};
  string.split('').forEach(function(s) {
     count[s] ? count[s]++ : count[s] = 1;
  });
  return count;
}

This was a fun one!