I am attempting (unsuccessfully) to write JavaScript function LetterCount to count the consecutive letters in a string (and not the total number).
Ideally:
LetterCount("eeeeeoooohhoooee") = [["e", 5],["o",3],["h",2],["o",3],["e",2]]
The following code attempts to count the number of consecutive letters in a string only when I already know what they are:
function LetterCount(str) {
for (var i=0; i<str.length;i++) {
var arr1=[]; arr2=[]; arr3=[]; arr4=[]; arr5=[];
var e=0; o=0; h=0; o2=0; e2=0;
if(str[i]="e") {
arr1 += "e";
e++;
}
arr1.push(e);
if(str[i]="o") {
arr2 += "o";
o++;
}
arr2.push(o);
if(str[i]="h") {
arr3 += "h";
h++;
}
arr3.push(h);
if(str[i]="o") {
arr4 += "o";
o2++;
}
arr4.push(o2);
if(str[i]="e") {
arr5 += "e";
e2++;
}
arr5.push(e2);
}
return arr1.concat(arr2).concat(arr3).concat(arr4).concat(arr5);
}
In the code above, I need to first know what the letters in the string are, and how many of them are present, in what order.
INSTEAD: How do you write a function that will automatically recognize the letter themselves, and then return the count of consecutive letters. Would also be great if the answer is in the following format:
LetterCount("eeeeeoooohhoooee") = [["e", 5],["o",3],["h",2],["o",3],["e",2]]
Any help is much appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…