24

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.

Community
  • 1
  • 1
JS-coder
  • 3,073
  • 2
  • 12
  • 14

19 Answers19

22

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]);
}
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
20

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}
Avatar
  • 12,849
  • 8
  • 110
  • 182
Vitaly Volynsky
  • 303
  • 2
  • 3
  • Welcome to SO. Your answer will be more useful if you include more explanation of how your code answers the question. – Nick Apr 05 '19 at 17:27
  • 9
    I would rather do `[...s].reduce((res, char) => (res[char] = (res[char] || 0) + 1, res), {})` – Yevgen Gorbunkov Jun 03 '19 at 08:30
  • Note that the result is not array, so you cannot use `result.length`, instead to check the length you would use `Object.keys(result).length`. – Avatar Jan 29 '20 at 10:39
6
let str = "atul kumar srivastava";
let obj ={};
for(let s of str)if(!obj[s])obj[s] = 1;else obj[s] = obj[s]  + 1;
console.log(obj)
4

I iterated over each character and put it in a nested object along with the count. If the character already exists in the object, I simply increment the count. This is what myObj looks like:

myObj = {
char1 = { count : <some num> },
char2 = { count : <some num> },
....
}

Here is the code:

function countChar(str) {
    let myObj= {};
    for (let s of str) {
        if ( myObj[s] ? myObj[s].count ++ : myObj[s] = { count : 1 } );
    }
    return myObj;
}

var charCount = countChar('abcceddd');
3

This worked well for me :

function Char_Count(str1) {
    var chars = {};
    str1.replace(/\S/g, function(l){chars[l] = (isNaN(chars[l]) ? 1 : chars[l] + 1);});
    return chars;
}

var myString = "This is my String";
console.log(Char_Count(myString));
kevinSpaceyIsKeyserSöze
  • 2,831
  • 2
  • 16
  • 22
3

You can use the maps in ES6 in Javascript. Provides a cleaner and concise code in my opinion. Here is how I would go about

function countChrOccurence ('hello') {
 let charMap = new Map();
 const count = 0;
  for (const key of str) {
   charMap.set(key,count); // initialize every character with 0. this would make charMap to be 'h'=> 0, 'e' => 0, 'l' => 0, 
  }

  for (const key of str) {
    let count = charMap.get(key);
    charMap.set(key, count + 1);
  }
// 'h' => 1, 'e' => 1, 'l' => 2, 'o' => 1

  for (const [key,value] of charMap) {
    console.log(key,value);
  }
// ['h',1],['e',1],['l',2],['o',1]
}  

2

I am giving you very very simple code.

 // Converts String To Array
        var SampleString= Array.from("saleem");

        // return Distinct count as a object
        var allcount = _.countBy(SampleString, function (num) {
            return num;
        });

        // Iterating over object and printing key and value
        _.map(allcount, function(cnt,key){
            console.log(key +":"+cnt);
        });

        // Printing Object
        console.log(allcount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

    <p>Set the variable to different value and then try...</p>
    
2
str = "aaabbbccccdefg";

words = str.split("");

var obj = [];

var counter = 1, jump = 0;

for (let i = 0; i < words.length; i++) {
    if (words[i] === words[i + 1]) {
        counter++;
        jump++;
    }
    else {
        if (jump > 0) {
            obj[words[i]] = counter;
            jump = 0;
            counter=1
        }
        else
            obj[words[i]] = 1;
    }

}
console.log(obj);
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/9193372) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made. – Syscall Mar 22 '21 at 16:35
2

A 1-liner ES6 way:

const some_string = 'abbcccdddd';
const charCountIndex = [ ...some_string ].reduce( ( a, c ) => ! a[ c ] ? { ...a, [ c ]: 1 } : { ...a, [ c ]: a[ c ] + 1 }, {} );
console.log( charCountIndex )
Siddharth Thevaril
  • 3,656
  • 3
  • 31
  • 65
2

You can use an object for a task.

Step 1 - create an object

step 2 - traverse through a string

Step 3 - add character as key and character count as value in the object

var obj={}

function countWord(arr)
{
for(let i=0;i<arr.length;i++)
{
if(obj[arr[i]]) //check if character is present in the obj as key
{
    obj[arr[i]]=obj[arr[i]]+1; //if yes then update its value
}
else
{
    obj[arr[i]]=1; //initialise it with a value 1

}
}
}

Pranay kumar
  • 1,665
  • 2
  • 16
  • 35
1
    function cauta() {

        var str = document.form.stringul.value;
        str = str.toLowerCase();
        var tablou = [];

        k = 0;
        //cautarea caracterelor unice
        for (var i = 0, n = 0; i < str.length; i++) {
            for (var j = 0; j < tablou.length; j++) {
                if (tablou[j] == str[i]) k = 1;
            }
            if (k != 1) {
                if (str[i] != ' ')
                    tablou[n] = str[i]; n++;
            }
            k = 0;
        }
        //numararea aparitilor
        count = 0;
        for (var i = 0; i < tablou.length; i++) {
            if(tablou[i]!=null){
            char = tablou[i];
            pos = str.indexOf(char);
            while (pos > -1) {
                ++count;
                pos = str.indexOf(char, ++pos);

            }

            document.getElementById("rezultat").innerHTML += tablou[i] + ":" + count + '\n';
            count = 0;
        }
        }

    }

This function will put each unique char in array, and after will find the appearances of each char in str. In my Case, i get and put data into

Dumitru Boaghi
  • 173
  • 2
  • 4
1

 // Converts String To Array
        var SampleString= Array.from("saleem");

        // return Distinct count as a object
        var allcount = _.countBy(SampleString, function (num) {
            return num;
        });

        // Iterating over object and printing key and value
        _.map(allcount, function(cnt,key){
            console.log(key +":"+cnt);
        });

        // Printing Object
        console.log(allcount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

    <p>Set the variable to different value and then try...</p>
    
1

Hope this helps someone

function getNoOfOccurences(str){
    var temp = {};
    for(var oindex=0;oindex<str.length;oindex++){
        if(typeof temp[str.charAt(oindex)] == 'undefined'){
            temp[str.charAt(oindex)] = 1;
        }else{
            temp[str.charAt(oindex)] = temp[str.charAt(oindex)]+1;
        }
    }
    return temp;
}
1
    package com.company;

import java.util.HashMap;


 public class Main {

    public static void main(String[] args) {
    // write your code here
    HashMap<Character, Integer> sHashMap = new HashMap();  // using hashMap<key , value > here key = character and  value = count

    String arr = "HelloWorld";

    for (int i = 0; i < arr.length(); i++) {
        boolean flag = sHashMap.containsKey(arr.charAt(i));  // check if char is already  present 

    if (flag == true)
        {
            int Count = sHashMap.get(arr.charAt(i)); // get the char count
            sHashMap.put(arr.charAt(i), ++Count); //   increment the count and update in hashMap
        } 
        else 
        {
            sHashMap.put(arr.charAt(i), 1); //if  char not present then insert into hashMap
        }
    }

     System.out.println(sHashMap);
    //OutPut would be like ths {r=1, d=1, e=1, W=1, H=1, l=3, o=2}

}

}
  • Hey there! This is a code only answer which has very little value to anyone else. Might I request you to include some explanation around _what_ the code does? Thanks! – 10 Rep Feb 01 '21 at 17:29
1

I have used Map object , The map object doesn't let you set any duplicate key and that makes our job easy . I am checking if the key already exists in map , if not I am inserting and setting the count to 1 , if it already exists I am getting the value and then incrementing

const str = "Hello H"
    const strTrim = str.replace(/\s/g,'') // HelloH
    const strArr=strTrim.split('')

    let myMap = new Map(); // Map object 

    strArr.map(ele=>{
    let count =0
    if(!myMap.get(ele)){
    myMap.set(ele,++count)
    }else {
    let cnt=myMap.get(ele)
    myMap.set(ele,++cnt)
    }
    console.log("map",myMap)
    })
Vishwanath
  • 172
  • 1
  • 12
1
let newStr= "asafasdhfasjkhfweoiuriujasfaksldjhalsjkhfjlkqaofadsfasasdfas";
       
function checkStringOccurnace(newStr){
    let finalStr = {};
    let checkArr = [];
    let counterArr = [];
    for(let i = 0; i < newStr.length; i++){
        if(checkArr.indexOf(newStr[i]) == -1){
            checkArr.push(newStr[i])
            let counter = 0;
            counterArr.push(counter + 1)
            finalStr[newStr[i]] = 1;
        }else if(checkArr.indexOf(newStr[i]) > -1){
            let index = checkArr.indexOf(newStr[i])
            counterArr[index] = counterArr[index] + 1;
            finalStr[checkArr[index]] = counterArr[index];
        }
    }
    return finalStr;
}

let demo = checkStringOccurnace(newStr);
console.log(" finalStr >> ", demo);
Blizzardengle
  • 896
  • 20
  • 27
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Remi Mar 23 '21 at 17:10
  • This is a great answer to an old question. I would recommend fixing your formatting and adding some comments. Also, if your going to provide a function its best to return something and do the console log outside the function as an example. – Blizzardengle Mar 24 '21 at 03:34
1

I tried it with chceking "empty space" as well as "special characters":

function charCount(str){
    const requiredString = str.toLowerCase();

    const leng = str.length;

    let output = {};

    for(let i=0; i<leng; i++){
        const activeCharacter = requiredString[i];
        if(/[a-z0-9]/.test(activeCharacter)){
            output.hasOwnProperty(activeCharacter) ? output[activeCharacter]++ : output[activeCharacter] = 1;
        }
    }
    return output;
}
Narayan Shrestha
  • 596
  • 5
  • 17
0

Split the string with the spread ... operator instead of .split(''):

''.split('')
//=> ["\ud83c", "\udf2f", "\ud83c", "\udf2f", "\ud83c", "\udf63", "\ud83c", "\udf7b"]

vs

[...'']
//=> ["", "", "", ""]

vs

''.charAt(0)
//=> "\ud83c"

Then reduce:

[...''].reduce((m, c) => (m[c] = (m[c] || 0) + 1, m), {})
//=> {'': 2, '': 1, '': 1}
customcommander
  • 14,568
  • 4
  • 48
  • 68
0

To check and avoid spaces and convert capital letters to small and count we can do like below.

function CountNumberOfCharacters(str) {
  let countObject = {};
  const lowerCaseString = str.toLowerCase();
  for (let char of lowerCaseString) {
    if (!countObject[char] && char !== ' ') {
      countObject[char] = 1;
    } else if (char !== ' ') {
      countObject[char] = countObject[char] + 1;
    }
  }
  return countObject;
}
Sharad Pawar
  • 251
  • 1
  • 2
  • 16