Reputation: 11
How to find if all distinct characters in a sting have the same count for example aassdd
has the same count of 'a', 's' and 'd'
. I know how to compare characters to each other but i don't know where to hold the numbers of each occurance
function letterCount(string, letter, caseSensitive) {
var count = 0;
if ( !caseSensitive) {
string = string.toUpperCase();
letter = letter.toUpperCase();
}
for (var i=0, l=string.length; i<string.length; i += 1) {
if (string[i] === letter) {
count += 1;
}
}
return count;
}
My question is how to hold the number of each character occurance and than to compare them
Upvotes: 0
Views: 128
Reputation: 386540
You could use an object and the characters as property for count.
function letterCount(string, caseSensitive) {
var count = {};
if (!caseSensitive) {
string = string.toUpperCase();
}
for (var i = 0, l = string.length; i < l; i++) {
if (!count[string[i]]) {
count[string[i]] = 0;
}
count[string[i]]++;
}
return count;
}
console.log(letterCount('aAssdD', false));
console.log(letterCount('aAssdD', true));
Upvotes: 2