I’m currently attending a coding bootcamp and I’m really struggling with an algorithm challenge we were given for homework.
here it is:
// write a function to return the number of occurances of each letter of a string in an object case insensive
// eg. numOfOccurances(‘This is great’) => { t: 2, h: 1, i: 2, s: 2, g: 1, r: 1, e: 1, a: 1 }
I would start by thinking about what I need done, and then all the steps I would need to take to do that.
For instance, you need to check every character in a given string, the most obvious thing to do is use a for loop. Since it’s case insensitive, you can make the string lowercase to simplify before looping over it. You’ll need to make an object to store your characters in.
Yeah, I understand that. I’ve been working on it for a while and I thought I could use some help. But fair enough, I’ll take a break and try again in a bit
To elaborate on what AlexMcLeod01 suggested:
I’d write a function that accepts a string and a substring (a letter in our case) and checks how many occurrences of this substring there are in our string.
function check_str(el,str) {
var count = 0;
for (let i = 0;i<str.length;i++) {
if (str[i]===el) {
count++;
}
}
return count;
}
Now you have to apply this function to the set of letters in your string and push an object that looks like {letter:check_str(letter,str)} to an array. Hope that helps.