Finding the character with longest consecutive repetitions in a string and its length using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string. Our function should return an array of exactly two elements the first element will be characters that makes the most number of consecutive appearances in the string and second will be its number of appearances.

Example

Following is the code −

 Live Demo

const str = 'tdfdffddffsdsfffffsdsdsddddd';
const findConsecutiveCount = (str = '') => {
   let res='';
   let count=1;
   let arr = []
   for (let i=0;i<str.length;i++){
      if (str[i]===str[i+1]){
         count++
      } else {
         if (arr.every(v=>v<count)){
            res=str[i]+count
         }
         arr.push(count)
         count=1
      }
   }
   return !res?['',0]:[res.slice(0,1),res.slice(1)*1];
};
console.log(findConsecutiveCount(str));

Output

['f', 5]
raja
Updated on 20-Apr-2021 09:44:26

Advertisements