![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the character with longest consecutive repetitions in a string and its length using JavaScript
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 −
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]
Advertisements