Dell Watson - 1 year ago 153
Javascript Question

# Javascript count repeating letter

I'm new student in here,sorry for asking simple question and I'm trying to solve a problem to count a same letter.

``````Input:"aabbcde"
cause a = 2, b= 2, c= 1 , d =1 , e = 1
Output:"2a2b1c1d1e" or a2b2c1d1e1
``````

and here's my code unfinished, I stucked

``````function repeatL(str) {
var word = str.split("").sort();
var temp = 0;
var i =1;
while(i< word.length){
if(word[i] === word[i +1]) {
//return temp to array of a += 1 ?
};
}
}
repeatL("abbbdd"); //output should be a1b3d2
``````

also what if the input is not string but an array:

``````Input:[a,ab,bc,d,e]
``````

is that even possible to solved?

You could use a variable for the result string, start with a count variable with 1 and iterate with a check of the former and actual letter. Then either count or move the count to the result set with the last letter. Reset counter to one, because the actual letter count is one.

At the end, finish the result with the last count and the letter, because one letter is not propcessed with the count (remember, you start with index 1, and you look always to the letter before of the actual index)

``````function repeatL(str) {
var word = str.split("").sort(),
count = 1,
i = 1,
result = '';

while (i < word.length) {
if (word[i - 1] === word[i]) {
count++;
} else {
result += count + word[i - 1];
count = 1;
}
i++;
}
result += count + word[i - 1];
return result;
}

console.log(repeatL("aabbcde"));``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download