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 -> 1
count of l -> 3
count of o -> 2
count of r -> 1
count of d -> 1
count of W -> 1
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 -> 1
count of l -> 3
count of o -> 2
count of r -> 1
count of d -> 1
count of W -> 1
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;
}, {});
Array.map and Array.reduce are only natively supported in IE9+. Other browsers should be fine for most versions. See this browser compatibility chartthis 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]);
}
Below is my solution with the old and simple for loop. This approach answers the question in the simplest possible way for beginners. This code will convert all the letters in the input to lower case and count their occurrence. In this solution, we also count the special characters and spaces as valid characters.
function countChar(str) {
var count = {};
for (let i = 0; i < str.length; i++) {
var ch = str[i].toLowerCase();
if (count[ch] > 0) {
count[ch]++;
} else {
count[ch] = 1;
}
}
return count;
}
The count object denotes the characters in the input.