Each Character occurrence in a string

前端 未结 3 1107
不知归路
不知归路 2021-01-17 05:12

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 -&         


        
相关标签:
3条回答
  • 2021-01-17 05:26

    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]); 
    }
    
    0 讨论(0)
  • 2021-01-17 05:27
    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);
    
    0 讨论(0)
  • 2021-01-17 05:29
    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;
    }, {});
    
    0 讨论(0)
提交回复
热议问题