Finding the longest consecutive appearance of a character in another string using JavaScript


Problem

We are required to write a JavaScript function that takes in a string as the first argument and a single character as the second argument.

Our function should count and return the longest consecutive appearance of the the character in the string.

Example

Following is the code −

 Live Demo

const str = 'abcdaaadse';
const char = 'a';
const countChars = (str = '', char = '') => {
   const arr = str.split('');
   let c = 0, max = 0;
   for (let i = 0; i<arr.length ;i++){
      if(arr[i] === char){
         c+=1
         if(c > max){
            max = c;
         };
      }else{
         if(c > max){
            max = c;
         };
         c = 0;
      };
   };
   return max;
};
console.log(countChars(str, char));

Output

3

Updated on: 20-Apr-2021

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements