javascriptfor-loopindexoffor-in-looplastindexof

Is it okay to use for in loop on a string?


Just wondering if its acceptable to use a for in loop on a string. Not sure if there could be weird results or bad practice but my solution works at least in this example.

Coding practice question. Also, if anyone has a way to improve my solution I'm open to advice.

function firstNonRepeatingLetter(str) {
  const lowerStr = str.toLowerCase();

  for (let char in lowerStr) {
    if (lowerStr.lastIndexOf(lowerStr[char]) === parseInt(char) && 
    lowerStr.indexOf(lowerStr[char]) === parseInt(char)) {
      return str[char];
    }
  }

  return "";
}

Write a function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string.

Examples:

firstNonRepeatingLetter('a') => 'a'
firstNonRepeatingLetter('stress') => 't'
firstNonRepeatingLetter('sTreSS') => 'T'

Solution

  • While your code is working, I suggest to take an index for iterating the characters of a string.

    But your approach iterates the string to much by using indexOf and lastIndexOf. This could be changed by using a loop storing the last found index of the character.

    In another loop, compare the actual index with the stored one for the same character and return if equal.

    function firstNonRepeatingLetter(str) {
        var lowerStr = str.toLowerCase(),
            hash = {},
            i;
    
        for (i = 0; i < lowerStr.length; i++)
            hash[lowerStr[i]] = i;
    
        for (i = 0; i < lowerStr.length; i++)
            if (hash[lowerStr[i]] === i)
                return str[i];
    
        return "";
    }
    
    console.log(firstNonRepeatingLetter('a'));      // a
    console.log(firstNonRepeatingLetter('stress')); // t
    console.log(firstNonRepeatingLetter('sTreSS')); // T