2

Write a function called strLetterCount which accepts a string and returns a new string with each character followed by by the number of times it appears in the string.

For example:

strLetterCount("taco"); // "t1a1c1o1"

My code is way off the mark here but this is what I got...

I was going to keep going for each letter and then from try and return the correct string. I know this is not a good way to go about it. Any help?

function strLetterCount(str) {

  var countA = 0;
  var countB = 0;
  var countC = 0;
  var countD = 0;
  var countE = 0;
  var countF = 0;
  var countG = 0;
  var countH = 0;
  var countI = 0;
  var countJ = 0;
  var countK = 0;
  var countL = 0;
  var countM = 0;
  var countN = 0;
  var countO = 0;
  var countP = 0;
  var countQ = 0;
  var countR = 0;
  var countS = 0;
  var countT = 0;
  var countU = 0;
  var countV = 0;
  var countW = 0;
  var countX = 0;
  var countY = 0;
  var countZ = 0;

  for (var i = 0; i < str.length; i++);
  if (str[i] === 'a') {
    countA++;
  }
  for (var i = 0; i < str.length; i++);
  if (str[i] === 'b') {
    countB++;
  }
  for (var i = 0; i < str.length; i++);
  if (str[i] === 'c') {
    countC++;
  }
  return {"a":countA,"b":countB,"c":countC}
}

console.log(
  strLetterCount("The quick brown fox jumps over the lazy dog")
)  
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Christian
  • 391
  • 3
  • 12
  • Check here [https://stackoverflow.com/questions/49035837/write-a-javascript-function-to-get-the-number-of-occurrences-of-each-letter-in-s] – Kuba Janik Apr 02 '20 at 12:10
  • *then from try and return the correct string* please elaborate on this – Rajesh Apr 02 '20 at 12:10
  • Is it case sensitive? Do you only need leters? – D. Pardal Apr 02 '20 at 12:10
  • 1
    Does this answer your question? [Count the number of occurrences of a character in a string in Javascript](https://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript) – Utsav Patel Apr 02 '20 at 12:11
  • 1
    I suggest you use an object to keep each character as a key and the appearance/frequency count as the value. Whenever you see a new character, you can add it as a new key with a value of `1`. If you see a key/character already in the object, you can add to its value/frequency count. – Nick Parsons Apr 02 '20 at 12:15
  • I made you a snippet. Your for loops are terminating at the `;` so do not count at all – mplungjan Apr 02 '20 at 12:18
  • 1
    I've added an answer, I hope it helps! – Tamas Szoke Apr 02 '20 at 12:55

5 Answers5

1

Just loop through every character of the string, and count them in an object.

A simple solution would be:

let str = "The quick brown fox jumps over the lazy dog";

const count = string => {
  const characters = {};
  for (let character of string) {
    characters[character] = characters[character] + 1 || 1;
  }
  return characters;
}

console.log(count(str));

You can use the results as:

let result = count(str);
console.log(result["o"]); // 4

Update

If you need a string output, one option is to use a second loop to write out the results:

let str = "The quick brown fox jumps over the lazy dog";

const count = string => {
  const characters = {};
  let str = "";
  
  for (let character of string) {
    characters[character] = characters[character] + 1 || 1;
  }
  for (let key in characters) {
    str += `${key}${characters[key]}`
  }
  return str;
}

console.log(count(str));

Or, if you don't care about the format just simply:

return JSON.stringify(characters);
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
0

You can try this using Object.entries(), reduce() and flat() methods:

function strLetterCount(str) {
  return Object.entries([...str].reduce(function(ac, s) {
    ac[s] = ++ac[s] || 1
    return ac;
  }, {})).flat().join('')
}

console.log(strLetterCount("taco"))
console.log(strLetterCount("chocotaco"))

Explanation:

  1. Using [...str] we first convert the string into an array.
  2. Then using .reduce() we are trying to get the count of each string element and the store into an object like:

    {t: 1, a: 1, c: 1, o: 1}
    
  3. Then using Object.entries() we are getting data like:

    [["t", 1], ["a", 1], ["c", 1], ["o", 1]]
    
  4. And finally using flat() & join() we get the required output format as string like t1a1c1o1

palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

Simplest and most readable in my opinion

const countChars = str => {
  const chars = {};                  // create a counter object
  const arr = str.split("");         // make an array from the characters
  arr.forEach(char => chars[char] = ++chars[char] || 1) // add counters to counter object

  return arr                         // return the array but first
    .map(char => char + chars[char]) // map to counters
    .join("");                       // and then join to string
}

console.log(countChars("Now is the time"));

Reduced to just char + number in the order of the first occurrence

const countChars = str => {
  const chars = {};                  // create a counter object
  const arr = str.split("");         // make an array from the characters
  arr.forEach(char => chars[char] = ++chars[char] || 1) // add counters to counter object
  return Object.keys(chars)          // return the chars
    .map(char => char + chars[char]) // concatenated with counters
    .join("");                       // and then join to string
}
console.log(countChars("woof the looping loop"));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Is there a way to return the string without repeating numbers? For example: woof, would be w1o2f1 as opposed to w1o2o2f1? –  Nov 04 '20 at 00:50
  • @alexwhitmore - is the second example what you meant? – mplungjan Nov 04 '20 at 06:12
0

Here's a shorter way:

function strLetterCount(s) {
  return [...s].map(l=>l + s.split(l).length-1).join('')
}
  1. You use [...s] to turn the string into an array of its characters.

  2. Then iterate over each one.

  3. Replace it with the letter, plus the number of times it occurs in the string.

  4. Join the fragments together to make a string again.

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
-2

You can use an associative array instead of all those variables and write a single for to analyze the string.

function strLetterCount(str) {
  var map = [];
  for (var i = 0; i < str.length; i++) {
    if (map[str[i]] === undefined)
      map[str[i]] = 0;
    map[str[i]]++;
  }
  var res = "";
  for (var i = 0; i < str.length; i++)
    res += str[i] + map[str[i]];
  return res;
}
console.log(strLetterCount("taco"))

You can find some useful information here.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
S. Martelli
  • 80
  • 1
  • 2
  • How do you get rid of the repeating characters? If you had the word "woof", how do you get w1o2f1 as opposed to w1o2o2f1 ? –  Nov 04 '20 at 01:13