Count Characters
Write a function that takes a string and returns an object that counts the number of occurrences of each character in the string using a for loop.
countCharacters('hello')
, the function would return the following object:{
h: 1,
e: 1,
l: 2,
o: 1
}
Solution Walkthrough for Count Characters
Spoiler Alert!
Don't read this unless you've already solved the problem.
countCharacters
that takes a string str
as an argument and returns an object that counts the number of occurrences of each character in the input string using a for loop.Here's how it works:
charAt()
method to get the character at the current index i
in the string, and assigns it to a variable called char
.const char = str.charAt(i);
counts
object. If it does, it increments its count by 1. If it doesn't, it sets its count to 1.counts[char] = counts[char] ? counts[char] + 1 : 1;
counts[char]
is truthy. If it is, it increments its value by 1 (counts[char] + 1
). If it's falsy (i.e. undefined), it sets its value to 1.