I'm trying to solve this problem in JavaScript, but am having a hard time doing so.
Let's say that someone says a message like "yeah", I need to return "yyeeaahh"or if the frequency of each character was uneven in the original string:
"yyeaaahhh" then my function should return:
"yyyeeaaaahhhh"
My approach was as follows:
I started by turning the string into an Array of its characters.
After getting the Array, I decided to create a JavaScript object that has key value pairs in the sense where the keys are the letters and the values are how many times the letter appears in the string.
I then learned about the Object.entries() method which allows me to get an array of these key value pairs as arrays.
Where I am getting stuck is how do I map this array to a new array which contains the keys displayed (value + 1) times where value is the key's corresponding frequency in the original string.
In a more visual context I want go from this to this:
[['y', 2], ['e', 3], ['a', 3], ['h', 2]] => ['yyy', 'eeee', 'aaaa', 'hhh']
After this, I figure I can trivially join this array back into a string to get my resulting string.
Here's my code so far:
function newString(string) {
const strArr = string.split('')
var counts = {};
for (var i = 0; i < strArr.length; i++) {
if ((string.match(new RegExp(strArr[i], "g"))).length >= 1) {
counts[string[i]] = (string.match(new RegExp(string[i], "g"))).length;
}
}
var countArr = Object.entries(counts)
var newStrArr = []
for(const [key,value] in countArr) {
newStrArr.push(key.repeat(value + 1))
}
return newStrArr
}
[['y', 2], ['e', 3], ['a', 3], ['h', 2]] => ['yyy', 'eeee', 'aaaa', 'hhh']
abashould it beaabbaaoraaabbor something else?