Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of occurrences for each char in a string

Tags:

javascript

I want to count the number of occurrences of each character in a given string using JavaScript.

For example:

var str = "I want to count the number of occurances of each char in this string";

Output should be:

h = 4;
e = 4; // and so on 

I tried searching Google, but didn't find any answer. I want to achieve something like this; order doesn't matter.

like image 432
JS-coder Avatar asked Oct 20 '13 18:10

JS-coder


2 Answers

This is really, really simple in JavaScript (or any other language that supports maps):

// The string
var str = "I want to count the number of occurances of each char in this string";

// A map (in JavaScript, an object) for the character=>count mappings
var counts = {};

// Misc vars
var ch, index, len, count;

// Loop through the string...
for (index = 0, len = str.length; index < len; ++index) {
    // Get this character
    ch = str.charAt(index); // Not all engines support [] on strings

    // Get the count for it, if we have one; we'll get `undefined` if we
    // don't know this character yet
    count = counts[ch];

    // If we have one, store that count plus one; if not, store one
    // We can rely on `count` being falsey if we haven't seen it before,
    // because we never store falsey numbers in the `counts` object.
    counts[ch] = count ? count + 1 : 1;
}

Now counts has properties for each character; the value of each property is the count. You can output those like this:

for (ch in counts) {
    console.log(ch + " count: " + counts[ch]);
}
like image 75
T.J. Crowder Avatar answered Oct 14 '22 06:10

T.J. Crowder


Shorter answer, with reduce:

let s = 'hello';
var result = [...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {}); 
console.log(result); // {h: 1, e: 1, l: 2, o: 1}
like image 33
Vitaly Volynsky Avatar answered Oct 14 '22 07:10

Vitaly Volynsky