Advertisement
biswasrohit20

strCount

Jun 11th, 2021
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function strLetterCount (str){
  2.     // create an object to store each letter
  3.     const countObj = {}
  4.     // iterate over the string
  5.     for (let i = 0; i < str.length; i++) {
  6.         // if the letter isn't stored in the object, add it with a count of one
  7.         if (!countObj[str[i]]) {
  8.             countObj[str[i]] = 1;
  9.         } else {
  10.             // if the letter is already in the object, increment the count
  11.             countObj[str[i]]++;
  12.         }
  13.     }
  14.     // create a string to add the letter / count to
  15.     let outStr = "";
  16.     // iterate over the object to create the string
  17.     for (const letter in countObj) {
  18.         outStr += `${letter}${countObj[letter]}`;
  19.     }
  20.     // return the string
  21.     return outStr;
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement