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
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.