Just
Some Drops

JavaScript Challenges

Below are some JavaScript challenges that I've done on some online websites.

Finding the First Non-repeating Character in a String

In this problem, we are going to find the first non-repeating character in a given string. For example, in the text “Lorem Ipsum” the ‘L’ is the first non-repeating word. So, let's see how to solve this problem in JS.

function firstNonRepeatChar(str){
  var len = str.length,
      char, 
      charCount = {};
  for(var i = 0; i < len; i++){
    char = str[i];
    if(charCount[char]){
      charCount[char]++;
    }
    else
      charCount[char] = 1;
  }
    for (var j in charCount){
    if (charCount[j] == 1)
       return j;
  }
}

console.log(firstNonRepeatChar("Quick brown fox jumps over the lazy dog")) // returns Q

Code Explained:

Using for loop go through every word of the string. Check the character if it is presented in the declared object charCount. If it is true, then increase the count by 1. Or, initiate the count by 1. Thus we will finally get the char count of all the characters in the given string. But wait, that is not the solution for our problem. So lets check our object again.

Create another for loop, this time it is actually a for in loop. Then check if the current key value is equal to 1 (Remember, we need the first non-repeating character). If so, return the key value.