JavaScript Exercise: Find the Number of Unique Letters in a String

By  on  

Everyone once in a while it's good to complete a fun vanilla JavaScript exercise. One recent exercise I tried was to find the number of occurrences of each letter in specified string. The following was my method.

The JavaScript

/* returns the size/length of an object */
Object.size = function(obj) {
	var size = 0;
	for(key in obj) {
		if(obj.hasOwnProperty(key)) size++;
	}
	return size;
}

//initial vars
var str = 'hellodavidthisisatestofobjectusage';
var letters = new Object;

//loop, figure it out
for(x = 0, length = str.length; x < length; x++) {
	var l = str.charAt(x)
	letters[l] = (isNaN(letters[l]) ? 1 : letters[l] + 1);
}

//output count!
for(key in letters) {
	console.log(key + ' :: ' + letters[key]);
}
console.log(Object.size(letters));

The Result

h :: 2
e :: 4
l :: 2
o :: 3
d :: 2
a :: 3
v :: 1
i :: 3
t :: 4
s :: 4
f :: 1
b :: 1
j :: 1
c :: 1
u :: 1
g :: 1
16

The above results in 20 letters being found

Have a different solution? Share it!

Recent Features

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

  • By
    I&#8217;m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

  • By
    MooTools Font-Size Scroller with Cookie Save

    Providing users as many preferences as possible always puts a smile on the user's face. One of those important preferences is font size. I can see fine but the next guy may have difficulty with the font size I choose. That's why...

  • By
    :valid, :invalid, and :required CSS Pseudo Classes

    Let's be honest, form validation with JavaScript can be a real bitch.  On a real basic level, however, it's not that bad.  HTML5 has jumped in to some extent, providing a few attributes to allow us to mark fields as required or only valid if matching...

Discussion

  1. Wes

    This looks like the beginning of a simple javascript word game…you get the letters and amount of times they occur and then have to figure out the string.

  2. Here’s my attempt:

    var str = 'hellodavidthisisatestofobjectusage';
    var uniq = '';
    for (var i = 0; i< str.length; i++) {
     if(uniq.indexOf( str[i] ) == -1){
       uniq += str[i];
     }
    }
    console.log(uniq.length);
    

    This is probably self explanatory but it goes through and checks if the character is in the “uniq”ue string. If not, it adds it to the end. Then it just determines the length of the unique string, since all characters contained within are… unique. It’s basically the same as yours but it saves having to loop through the object keys just to get a count. I feel like there’s a regex way of doing this but I’m not sure how.

  3. Rakesh Juyal [RJ]

    Walsh, u certainly know how to perform the easiest task in the toughest way.

  4. My intention Rakesh was to keep the number of times each appeared — which I now realize I didn’t state. Jonathan’s solution looks great.

  5. My attempt:

    function letterCount(str) {
        var ret = {},
            len = str.length;
        str = str.split('').reverse();
        while (len--) ret[str[len]] = ret[str[len]] + 1 || 1;
        return ret;
    }
    

    It iterates (in reverse) through the string and adds a new property of that character to the returned object. It iterates in reverse because that’s quicker than the alternative – i.e. having to check the length property on every iteration…

  6. grigri
    function getCharCounts(s) {
      var letters = {};
      s.replace(/\S/g, function(l){letters[l] = (isNaN(letters[l]) ? 1 : letters[l] + 1);});
      return letters;
    }
    
    console.log(getCharCounts('hellodavidthisishowtodoitwithregularexpressions'));
    
  7. I forgot to mention, my function returns a very usable object, constructed like this: { h: 2, e: 4, l: 2, o: 3, etc…. }

  8. Oooh, I like that James.

  9. This is fun. :)

    var str = “hellodavidthisisatestofobjectusage”;
    var letters = {};

    for (var x = 0, y = str.length; x < y; x++) {
    letters[str[x]] = letters[str[x]] + 1 || 1;
    }

  10. hah! I just realized that the whole thing could be made smaller:

    var str = “hellodavidthisisatestofobjectusage”, letters = {};
    for (var x = 0, y = str.length; x < y; x++) letters[str[x]] = letters[str[x]] + 1 || 1;

    ^^b

  11. grigri

    Nice one keeto, this makes mine smaller too:

    var str='thisisultrashortwithregexps', letters={};
    s.replace(/\S/g, function(l){letters[l]=letters[l]+1||1);});
  12. Cute one, grigri. Although I forgot I could make mine even shorter:

    var str=’thisisultrashortwithregexps’, letters={};
    for (var x in str) letters[str[x]] = letters[str[x]] + 1 || 1;

    More David! More!

  13. Great solutions everyone! I added the Object.size() to be able to show a result so mine is pretty close to everyone’s.

    More in the future?

  14. rakesh juyal

    @Gri: nice use of regex.

  15. I like @grigri, with the correction of \w instead of \S because the OP said ‘letters’ :)

    Taking that into account, that’s the solution that most elegantly lets you count letters alone.

  16. This might be a great read:

    http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/

    Not the same thing, but brilliant as well.

  17. I am currently learning python so I did:

    s = ‘thisissomestringwithsomechars’
    count = {}
    for c in s:
    count[c] = count.get(c,0) + 1
    print count

    Which outputs:
    {‘a’: 1, ‘c’: 1, ‘e’: 2, ‘g’: 1, ‘i’: 4, ‘h’: 3, ‘m’: 2, ‘o’: 2, ‘n’: 1, ‘s’: 6, ‘r’: 2, ‘t’: 3, ‘w’: 1}

  18. Sucheta

    I m new to javascript.
    I want to find no of unique letters in a string using javascript.
    pls help me out

  19. Using reduce,

    function getLetterCount(arr){
        return arr.reduce(function(prev,next){
            prev[next] = (prev[next] + 1) || 1;
            return prev;
        },{});
    }
    
    console.log(getLetterCount("dfglksdhfglhjhkdjfhgfdg".split('')));
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!