Count number of occurrences for each char in a string

后端 未结 11 2342
挽巷
挽巷 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条回答
  •  别那么骄傲
    2020-12-16 18:22

    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}
    

提交回复
热议问题