Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript Count repeating letter


Suppose, we have a string like this −

const str = 'aabbcde';

Here, we have 2a's, 2b's 1c 1d and 1e

We are required to write a JavaScript function that takes in one such string. The function should then construct a string with the character count followed by the character.

Therefore, for the above string, the output should look like −

const output = '2a2b1c1d1e';

Example

const str = 'aabbcde';
const repeatLetter = (str = '') => {
   const strArr = str.split("").sort();
   let count = 1;
   let i = 1;
   let res = '';
   while (i < strArr.length) {
      if (strArr[i - 1] === strArr[i]) { count++; }
      else {
         res += count + strArr[i - 1];
         count = 1;
      };
      i++;
   };
   res += count + strArr[i - 1];
   return res;
};
console.log(repeatLetter(str));

Output

This will produce the following output −

2a2b1c1d1e