2

How to write a javascript code that counts each character occurrence in a string ?

e.g 
String is : Hello World 

Output :  
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2 
count of r -> 1
count of d -> 1 
count of W -> 1 
1
  • i tried split, match but it didnt work ... Commented Feb 10, 2013 at 13:11

4 Answers 4

11
var counts = {};
yourstring.split('').map(function(ch) {
  counts[ch] = (counts[ch] || 0) + 1;
});

Or be hip and use map/reduce:

var counts = yourstring.split('').reduce(function(dst, c) {
  dst[c] = (dst[c] || 0) + 1;
  return dst;
}, {});
Sign up to request clarification or add additional context in comments.

1 Comment

The only thing to be mindful with this is that Array.map and Array.reduce are only natively supported in IE9+. Other browsers should be fine for most versions. See this browser compatibility chart
1

this code should work:

var str = "Hello World";
var arr = str.split('');
var occ = {};
for(var i=0,c=arr.length;i<c;i++){
    if(occ[arr[i]]) occ[arr[i]]++;
    else occ[arr[i]] = 1;
}
for(var i in occ){
    alert('count of '+i+' -> '+occ[i]); 
}

1 Comment

it's additional variable (see jsfiddle.net/8Denq) - on example 1 we get array's length and store it in "c" for further use, it gives far better perfomance than getting length property of an array in every loop (like in example 2) - you can read more about it here: openjs.com/articles/for_loop.php
0
var splitWord = "Hello World".split('');
var letters = {};
for(var i in splitWord)
{
    var letter = splitWord[i];
    if(letter == ' ') continue;
    if(typeof letters[letter] == 'undefined')
    {
        letters[letter] = 0;
    }
    letters[letter]++;
}
console.dir(letters);

Comments

0

Below is my solution with the old and simple for loop. This approach answers the question in the simplest possible way for beginners. This code will convert all the letters in the input to lower case and count their occurrence. In this solution, we also count the special characters and spaces as valid characters.

  function countChar(str) {
            var count = {};
            for (let i = 0; i < str.length; i++) {
                var ch = str[i].toLowerCase();
                if (count[ch] > 0) {
                    count[ch]++;
                } else {
                    count[ch] = 1;
                }
            }
            return count;
        }

The count object denotes the characters in the input.

1 Comment

Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See How to Answer. This is especially important when answering old questions (this one is over 8 years old) with existing answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.