Count number of occurrences for each char in a string

后端 未结 11 2349
挽巷
挽巷 2020-12-16 17:42

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         


        
11条回答
  •  旧时难觅i
    2020-12-16 17:58

    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]
    }  
    
    

提交回复
热议问题