CountLetters

CountLetters

Counting letters from string ___

##For Example console.log(countLetters(‘ffffeerttttooo’)) 4f,2e,1r,4t,3o ##


function countLetters(str) {
  let tempArray = str.split('');
  let letters = [];
  let count = 1;

  for (let i = 0;i<tempArray.length;i++) {
    if (tempArray[i] === tempArray[i+1]){
      count++
    }
    else {
      let value = `${count}${tempArray[i]}`;
      letters = [...letters,value]
      count = 1;
    }
  }
  
  return letters.join();
}

console.log(countLetters('ffffeerttttooo'))




First we create a function countLetters(str) { with the string as a parameter. Then we split the string into an array with the split JavaScript build in function that transforms string into an array.
We create empty array called letters and we create a counter called count and we initialize to 1.
We create for loop to loop through the array we created with spliting the string str and we check if (tempArray[i] === tempArray[i+1]) so we check if the current string is equal to the next string we increase the count with count++
else {
let value = ${count}${tempArray[i]};
letters = […letters,value]
count = 1;
}
}

return letters.join(); }
And in the else statement we create a value variable that holds the count and the string
letters array we push with spread operator to the new letters and its new values
and every time we have new value we start the counter to 1;
At the end we return letters array with join() build in JavaScript function that joins the array into string/ or it converts into string.

comments powered by Disqus