-4

Basically i'm trying to write function that takes GGHTTYYYD and returns 2GH2T3YD. Notice that numbers going first. I'm trying to write it in javascrript. How this can be done? Basically here i s my code:

let s = 'GGHTTYYYD';

const count = (str) => {
  let hash = {};
  str.split('').forEach((char) => {
    hash[char] = hash[char] ? (hash[char] += 1) : 1;
  });
  return hash
};

now i stuck at converting object named hash to string and filter all "1"

  • 1
    *I'm trying to write it in javascrript* Where are you trying to do so? Please post what you're trying to do so we can see where it's failing if you want debugging help – CertainPerformance May 29 '20 at 00:26
  • Assuming that you are attempting to count the number of occurrences of each character in the initial string, [this post](https://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript) might be a good starting place – Nick S May 29 '20 at 00:33

2 Answers2

1

It is a python implementation but I think it is straight-forward. I hope it helps!

def func(st):
# string to be formed
new_st = ""
# current character
curr_char = st[0]
# current character repeat count
curr_char_times = 1
for char in st[1:]:
    # character changed
    if char != curr_char:
        # if times is 1 do not write 1
        if curr_char_times == 1:
            new_st += curr_char
        else:
            new_st += str(curr_char_times)+curr_char
        # return back to initial state
        curr_char = char
        curr_char_times = 1
    else:
        # if character not changed increment times
        curr_char_times += 1
# process the last char
if curr_char_times == 1:
    new_st += curr_char
else:
    new_st += str(curr_char_times)+curr_char
return new_st
1

Using a JavaScript object as a map, then converting it to a string:

let inputStr="GGHTTYYYD"

const freqCount = (str) =>{

    const map={};

    //create a frequency map using a Javascript Object
    for(let c of str){
        map[c] = map[c] ? map[c]+1 : 1;
    }

    let outputStr="";

    for(let key in map){
        //add an if so we don't log 1's, print out the frequency
        if(map[key]!==1){outputStr+=map[key];}
        //add the letter no matter what
        outputStr+=key;
    }

    return outputStr;
}

console.log(freqCount(inputStr));
//2GH2T3YD
Mark Colby
  • 191
  • 6