🚀 Check out my $1,000,000 journey!

JavaScript Coding Challenge: "Counting Letters"

2 min read

JCC Counting Letters

Problem description

Given a string, count the number of occurrences of all of its letters.

Some cases:

'aabbcc' => { a: 2, b: 2, c: 2 }

'abcccd' => { a: 1, b: 1, c: 3, d: 1 }

Before reading forward, make sure you first try to solve the problem yourself. When you’re done you can come back and see how I’m going to solve it.

Basically what we have to do is to loop over the letters of the word and then save “somewhere” the number of times each letter appears.

I’ve chose this “somewhere” to be an object and every appearance of a letter will be a property, and the number of times it appears will be the value.

Let’s see how to do just that. 😄

Solution one - the for loop

const countLetters = word => {
	// Create the object which will store the occurrences
	const count = {};

	// Loop over the letters of the word
	for (let i = 0; i < word.length; i++) {
		const letter = word[i];

		// if the property isn't in the object, it means that the letter is a new one and we'll create this property and assign it the value 1
		if (!count[letter]) {
			count[letter] = 1;

			// else, it means that the property is already there and we just increment it by 1
		} else {
			count[letter]++;
		}
	}

	return count;
};

Solution two - the forEach

We can go one step further and instead of using a simple for loop, we can take advantage of a couple of things:

  1. the split method - which splits the letters from the string into an array
  2. the forEach method - which goes over the array and gives us access to each of its items/letters
  3. a ternary operator - which is basically doing the same as the if statement from above, but more elegantly 😃
const countLetters = word => {
	const count = {};

	word.split('').forEach(letter => {
		count[letter] = count[letter] ? ++count[letter] : 1;
	});

	return count;
};

Conclusion

I hope you enjoyed this Coding Challenge. Let me know if you find another method to solve it!

Happy Coding! 😇

    Want to stay updated?
    Sign up for the newsletter.

    No spam. Unsubscribe at any time.