Input: "aaabzzzaafff" Output: "3a1b3z2a3f"

by Yury

JavaScript

/*
Given a string, entirely consisting of lowercase letters a-z, collapse runs of these characters into the number of repeats followed by the character itself. For example:
 
Input: "aaabzzzaafff"
Output: "3a1b3z2a3f"
*/


function charsNumber(str){
    
    var arr = str.split();
    var totalArr =[];
    var charArr = [];
    
    arr.forEach((item) => {
         if (charArr && charArr.indexOf(item) >= 0){
             charArr.push(item);
         } else if(charArr && charArr.length && charArr.indexof(item) < 0 ){
             totalArr.push(charArr);
            charArr = [];
            charArr.push(item);
             
         } else if (!charArr.length && charArr.indexOf(item)<0){
             charArr.push(item);
         }
         
         total
         
        
    });
    
    
}