# Number of occurrences in a string?

Hi everyone,

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 }

function numOfOccurances(string) {

}

numOfOccurances(‘Feeling Like A Pro’)) => { f: 1, e: 3, l: 2, i: 2, n: 1, g: 1, k: 1, a: 1, p: 1, r: 1, o: 1 }

If anyone one has any solutions, ideas on how to complete this I would really appreciate it.

Thanks!

What have you done to solve this?

If you don’t like solving this kind of challenges, you won’t be happy as a programmer.

1 Like

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.

Try and figure it out from there.

1 Like

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

Thanks, this is actually pretty helpful!

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.

You can use reduce function to count no of character