return the first non repeating character in a string in javascript

You can use the indexOf method to find the non repeating character. If you look for the character in the string, it will be the first one found, and you won't find another after it:

function firstNonRepeatedCharacter(string) {
  for (var i = 0; i < string.length; i++) {
    var c = string.charAt(i);
    if (string.indexOf(c) == i && string.indexOf(c, i + 1) == -1) {
      return c;
    }
  }
  return null;
}

Demo: http://jsfiddle.net/Guffa/Se4dD/


If you're looking for the first occurrence of a letter that only occurs once, I would use another data structure to keep track of how many times each letter has been seen. This would let you do it with an O(n) rather than an O(n2) solution, except that n in this case is the larger of the difference between the smallest and largest character code or the length of the string and so not directly comparable.

Note: an earlier version of this used for-in - which in practice turns out to be incredibly slow. I've updated it to use the character codes as indexes to keep the look up as fast as possible. What we really need is a hash table but given the small values of N and the small, relative speed up, it's probably not worth it for this problem. In fact, you should prefer @Guffa's solution. I'm including mine only because I ended up learning a lot from it.

function firstNonRepeatedCharacter(string) {
   var counts = {};
   var i, minCode = 999999, maxCode = -1;
   for (i = 0; i < string.length; ++i) {
        var letter = string.charAt(i);
        var letterCode = string.charCodeAt(i);
       if (letterCode < minCode) {
           minCode = letterCode;
       }
       if (letterCode > maxCode) {
           maxCode = letterCode;
       }
        var count = counts[letterCode];
        if (count) {
           count.count = count.count + 1;
        }
        else {
            counts[letterCode] = { letter: letter, count: 1, index: i };
        }
   }

    var smallestIndex = string.length;
    for (i = minCode; i <= maxCode; ++i) {
       var count = counts[i];
       if (count && count.count === 1 && count.index < smallestIndex) {
          smallestIndex = count.index;
       }
   }

    return smallestIndex < string.length ? string.charAt(smallestIndex) : '';
}

See fiddle at http://jsfiddle.net/b2dE4/

Also a (slightly different than the comments) performance test at http://jsperf.com/24793051/2

Tags:

Javascript